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


140

当我发出发布请求时,Angular 2 http没有发送此请求

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

http帖子不会发送到服务器,但是如果我发出这样的请求

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

这是故意的,如果有人可以解释我为什么?还是一个错误?

Answers:



47

如果要执行调用,必须订阅返回的observable。

另请参见Http文档

永远订阅!

HttpClient您调用该方法返回的可观察对象之前,该方法不会开始其HTTP请求。所有 HttpClient 方法都是如此。

AsyncPipe订阅(和取消)为您自动。

HttpClient方法返回的所有可观察对象在设计上都是的。HTTP请求的执行被推迟,允许您通过其他操作(例如tapcatchError在实际发生任何事情之前)扩展可观察对象。

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

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

实际上,每个都会subscribe()启动可观察对象的单独,独立执行。订阅两次将导致两个HTTP请求。

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

41

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

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();
    }
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.