我是Angular2的新手并且正在建立一个示例项目来学习它.我正在寻找如何在Angular2中进行HTTP调用并找到此代码段示例:
var headers = new Headers(); headers.append('Content-Type','application/json'); this.http.post('http://www.Syntaxsuccess.com/poc-post/',JSON.stringify({firstName:'Joe',lastName:'Smith'}),{headers:headers}) .map((res: Response) => res.json()) .subscribe((res:Person) => this.postResponse = res);
我不确定订阅的作用,但我的主要目标是打印响应.从这段代码我可以看到响应,但我不确定如何“隔离和访问它”(我希望这是有道理的).我的问题是如何将响应打印到控制台?
解决方法
My question is how would I print the response to the console?
你可以打印res:
.subscribe((res:Person) => { this.postResponse = res; console.log(res); });
I am not sure what the subscribe does (…)
Http.post(...)
(link)的结果是Observable<Response>
(link).
在您的代码中,您选择POST的结果(Observable< Response>)并在其上调用.map()
(link).在您的情况下,您这样做是为了将响应解析为JSON并将其转换为对象:
.map((res: Response) => res.json())
现在,.map()的结果也是一个Observable< Response>.那是你打电话订阅的时候.
subscribe()
(link)是Observable
(link)类的一种方法,它允许你通过“注册”或“订阅”三个函数来处理/读取这个可观察到的结果(或“事件”) – 它们被称为(on)next,(上)错误和(上)完成.
因此,使用.subscribe()的代码通常是:
.subscribe( (response) => { /* this function is executed every time there's a new output */ console.log("VALUE RECEIVED: "+response); },(err) => { /* this function is executed when there's an ERROR */ console.log("ERROR: "+err); },() => { /* this function is executed when the observable ends (completes) its stream */ console.log("COMPLETED"); } );
所以,为了完全理解Angular2的Http,我建议你在RxJS and Observables上阅读一些资源.当你从中恢复时,事情将变得更加简单,我保证(没有双关语:).