繁体   English   中英

如何在Angular2中进行HTTP POST调用并打印响应

[英]How to make HTTP POST call in Angular2 and print the response

我是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); });

点击这里获取demo plunk


我不确定订阅的作用(...)

Http.post(...) (link)的结果是一个Observable<Response> (链接)

在您的代码中,您选择POST的结果(一个Observable<Response> )并在其上调用.map() (链接) 在您的情况下,您这样做是为了将响应解析为JSON并将其转换为对象:

.map((res: Response) => res.json())

现在, .map()的结果也是一个Observable<Response> 那是你打电话subscribe的时候。

subscribe() (link)Observable (link)类的一个方法,它允许你,“注册”或“订阅”三个函数来处理/读取这个可观察的发出的结果(或“事件”) - 它们被称为( onnext ,( onerror和( oncomplete

因此,使用.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和Observables的资源。 当你从它回来时,事情将变得更加简单,我保证(没有双关语:)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM