Angular 2 http.post() 没有发送请求

Angular 2 http.post() is not sending the request

当我发出 post 请求时,angular 2 http 未发送此请求

this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions())

http post 没有发送到服务器,但如果我这样发出请求

this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions()).subscribe(r=>{});

这是有意为之吗?如果是的话,有人可以解释一下为什么吗?或者这是一个错误?

由于 Http class returns 的 post 方法是一个可观察对象,因此您需要订阅它以执行其初始化处理。 Observable 是惰性的。

您应该观看此视频了解更多详情:

Get 方法不需要使用 subscribe 方法,但 post 方法需要 subscribe。获取和 post 示例代码如下。

import { Component, OnInit } from '@angular/core'
import { Http, RequestOptions, Headers } from '@angular/http'
import 'rxjs/add/operator/map'
import 'rxjs/add/operator/catch'
import { Post } from './model/post'
import { Observable } from "rxjs/Observable";

@Component({
    templateUrl: './test.html',
    selector: 'test'
})
export class NgFor implements OnInit {

    posts: Observable<Post[]>
    model: Post = new Post()

    /**
     *
     */
    constructor(private http: Http) {

    }

    ngOnInit(){
        this.list()
    }

    private list(){
        this.posts = this.http.get("http://localhost:3000/posts").map((val, i) => <Post[]>val.json())
    }

    public addNewRecord(){
        let bodyString = JSON.stringify(this.model); // Stringify payload
        let headers      = new Headers({ 'Content-Type': 'application/json' }); // ... Set content type to JSON
        let options       = new RequestOptions({ headers: headers }); // Create a request option

        this.http.post("http://localhost:3000/posts", this.model, options) // ...using post request
                         .map(res => res.json()) // ...and calling .json() on the response to return data
                         .catch((error:any) => Observable.throw(error.json().error || 'Server error')) //...errors if
                         .subscribe();
    }
}

如果要执行调用,您必须订阅返回的可观察对象。

另请参阅以下 angular 文档“Communicating with backend services using HTTP”。

Always subscribe!

An HttpClient method does not begin its HTTP request until you call subscribe() on the observable returned by that method. This is true for all HttpClient methods.

The AsyncPipe subscribes (and unsubscribes) for you automatically.

HttpClient 方法返回的所有 observables 都是 cold 设计的。 HTTP 请求的执行是 延迟的 ,允许您在任何实际发生之前使用 tapcatchError 等额外操作扩展可观察对象。

调用 subscribe(...) 会触发可观察对象的执行并导致 HttpClient 组合 HTTP 请求并将其发送到服务器。

您可以将这些可观察对象视为实际 HTTP 请求的蓝图

In fact, each subscribe() initiates a separate, independent execution of the observable. Subscribing twice results in two HTTP requests.

const req = http.get<Heroes>('/api/heroes');
// 0 requests made - .subscribe() not called.
req.subscribe();
// 1 request made.
req.subscribe();
// 2 requests made.