Angular 2中的http.post()未发送请求

182

当我进行一个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=>{});

这是有意为之的吗?如果是的话,有人能解释一下为什么吗?还是说这是一个错误?

3个回答

295

20
@Thiery:无法观看该视频,因为它只针对会员开放。 - Tatarin
总是 [我会忘记这个]。 - 10101010

81

如果你想让调用执行,你需要订阅返回的可观察对象。

还可以参考以下 Angular 文档 "使用 HTTP 与后端服务通信"

Starting the request

For all HttpClient methods, the method doesn't begin its HTTP request until you call subscribe() on the observable the method returns.

This is true for all HttpClient methods.

You should always unsubscribe from an observable when a component is destroyed.

All observables returned from HttpClient methods are cold by design. Execution of the HTTP request is deferred, letting you extend the observable with additional operations such as tap and catchError before anything actually happens.

Calling subscribe() triggers execution of the observable and causes HttpClient to compose and send the HTTP request to the server.

Think of these observables as blueprints for actual HTTP requests.

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.

另外一点需要注意的是:AsyncPipe会自动为您订阅(和取消订阅)。


48

使用Get方法不需要使用subscribe方法,但使用Post方法需要使用subscribe方法。以下是Get和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();
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接