angularjs – 如何在Angular2中进行HTTP POST调用并打印响应
我是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); 我不确定订阅的作用,但我的主要目标是打印响应.从这段代码我可以看到响应,但我不确定如何“隔离和访问它”(我希望这是有道理的).我的问题是如何将响应打印到控制台? 解决方法
你可以打印res: .subscribe((res:Person) => { this.postResponse = res; console.log(res); }); Click here for demo plunk.
在您的代码中,您选择POST的结果(Observable< Response>)并在其上调用 .map((res: Response) => res.json()) 现在,.map()的结果也是一个Observable< Response>.那是你打电话订阅的时候.
因此,使用.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上阅读一些资源.当你从中恢复时,事情将变得更加简单,我保证(没有双关语:). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |