加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-17 17:54:05 所属栏目:安全 来源:网络整理
导读:我是Angular2的新手并且正在建立一个示例项目来学习它.我正在寻找如何在Angular2中进行HTTP调用并找到此代码段示例: var headers = new Headers();headers.append('Content-Type','application/json');this.http.post('http://www.syntaxsuccess.com/poc-po
我是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); });

Click here for demo plunk.

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上阅读一些资源.当你从中恢复时,事情将变得更加简单,我保证(没有双关语:).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读