[英]Angular 4 Http Post put response in object
I'm using Angular 4 combined with an Asp.net web api. 我正在将Angular 4与Asp.net Web API结合使用。 I don't know how I can read the properties of my respond.
我不知道如何读取响应的属性。
My response looks likes this 我的回应看起来像这样
My post request: 我的帖子要求:
postLogin(values: string): Observable<string> {
let body = "username=test@test.test&password=Test1234!&grant_type=password";
/*let body = values + "&grant_type=password";*/
let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({headers: headers});
return this._http.post(this._postLoginUrl, body, options)
.catch(this.handleError);
}
And my actually call to the post method: 而我实际上对post方法的调用:
this._loginService.postLogin(value)
.subscribe(
data => console.log(data),
err => console.log(err));
And this does work, I do get the response in my Console 这确实有效,我确实在控制台中得到了响应
But how can I read my properties? 但是我该如何阅读我的财产?
UPDATE UPDATE
I've updated my code a bit but it still doesn't work like I want to, I did read the documentation but I still couldn't get further. 我已经对代码进行了一些更新,但是仍然无法如我所愿地工作,我确实阅读了文档,但是仍然无法继续。
My new call to the post method: 我对post方法的新调用:
console.log("username=" + this.username + "&password=" + this.password);
this._loginService.postLogin("username=" + this.username + "&password=" + this.password)
.subscribe(
user => this.user = user),
err => console.log(err);
And my new post request: 我的新帖子要求:
postLogin(values: string): Observable<User> {
let body = values + "&grant_type=password";
let headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
let options = new RequestOptions({headers: headers});
return this._http.post(this._postLoginUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
}
With as extractData function 带有as extractData函数
private extractData(res: Response) {
let body = res.json();
return body.fields || {};
}
If I do a console log of my user object now, I get undefined and if I try to access a property of user, my browser starts refreshing. 如果现在我对用户对象进行控制台日志,则无法定义,并且如果尝试访问user的属性,浏览器将开始刷新。 What I am doing wrong, why can't I access my data?
我做错了,为什么我不能访问我的数据?
Use 采用
JSON.parse(data._body)
this will give you the response object. 这将为您提供响应对象。
As you can see from your response, 从回应中可以看出,
{"access_token":"blaablaa", .... }
there is not any fields
in your data that you are receiving, but "just" an object with properties. 接收的数据中没有任何
fields
,而只是“带有”属性的对象。 Since there is no fields
, therefore you should only return the actual response: 由于没有
fields
,因此您应该只返回实际的响应:
private extractData(res: Response) {
let body = res.json();
return body || {}; // remove 'fields'
}
And when you are receiving your data you can easily access the fields 当您接收数据时,您可以轻松访问字段
this._loginService.postLogin(value)
.subscribe(data => {
console.log(data.access_token) // your access_token
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.