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

当我发出一个post请求angular2 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类的post方法返回一个observable,所以你需要订阅它来执行它的初始化处理。 观察者是懒惰的。

你应该看看这个video的更多细节:

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(); } }