[英]Angular 2 http.post() is not sending the request
当我发出帖子请求时,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
类的post
方法返回一个 observable,因此您需要订阅它以执行其初始化处理。 Observable 是惰性的。
您应该查看此视频以了解更多详细信息:
如果要执行调用,则必须订阅返回的 observable。
另请参阅以下角度文档“使用 HTTP 与后端服务通信”。
永远订阅!
HttpClient
方法不会开始其 HTTP 请求,直到您对该方法返回的 observable 调用subscribe()
。 这适用于所有HttpClient
方法。AsyncPipe会自动为您订阅(和取消订阅)。
从
HttpClient
方法返回的所有 observable 都是冷设计的。 HTTP 请求的执行被延迟,允许您在实际发生任何事情之前使用附加操作(例如tap
和catchError
扩展可观察catchError
。调用
subscribe(...)
会触发 observable 的执行,并导致HttpClient
组合并将 HTTP 请求发送到服务器。您可以将这些 observable 视为实际 HTTP 请求的蓝图。
事实上,每个
subscribe()
启动一个单独的、独立的 observable 执行。 订阅两次会产生两个 HTTP 请求。const req = http.get<Heroes>('/api/heroes'); // 0 requests made - .subscribe() not called. req.subscribe(); // 1 request made. req.subscribe(); // 2 requests made.
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();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.