Nic*_*icu 120 angular2-http angular
当我发帖请求时,角度2 http不发送此请求
this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions())
Run Code Online (Sandbox Code Playgroud)
http帖子没有发送到服务器,但如果我发出这样的请求
this.http.post(this.adminUsersControllerRoute, JSON.stringify(user), this.getRequestOptions()).subscribe(r=>{});
Run Code Online (Sandbox Code Playgroud)
这是有意的,如果有人可以解释我为什么?或者这是一个错误?
Thi*_*ier 201
由于类的post方法Http返回一个observable,您需要订阅它以执行其初始化处理.可观察者很懒惰.
您应该查看此视频以获取更多详细信息:
Igo*_*gor 41
如果要执行调用,则必须订阅返回的observable.
另请参阅Http文档.
总是订阅!
在
HttpClient您对该方法返回的observable调用subscribe()之前,方法不会开始其HTTP请求.所有HttpClient方法都是如此.该AsyncPipe订阅(和取消)为您自动.
从
HttpClient方法返回的所有可观测量都是冷设计.HTTP请求的执行被推迟,让您可观察到的额外行动扩展,如tap与catchError任何实际发生之前.调用
subscribe(...)触发observable的执行并导致HttpClient组合并将HTTP请求发送到服务器.您可以将这些可观察对象视为实际HTTP请求的蓝图.
实际上,每个都
subscribe()启动了一个独立的,独立的observable执行.订阅两次会导致两个HTTP请求.Run Code Online (Sandbox Code Playgroud)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.
Mur*_*NER 35
Get方法不需要使用subscribe方法,但post方法需要subcribe.获取和发布示例代码如下.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53513 次 |
| 最近记录: |