如何解析post请求响应中接收的javascript对象并在页面中显示它
下面是服务呼叫如何解析post请求响应中接收的javascript对象并在页面中显示它,javascript,angular,Javascript,Angular,下面是服务呼叫 this.http.post(this.apiurl, {'user': this.user}, { responseType: 'json' }) .subscribe((data) => { this.myRequests = JSON.stringify(data); const requests = JSON.parse(this.myRequests); this.Items = requests.
this.http.post(this.apiurl, {'user': this.user}, { responseType: 'json' })
.subscribe((data) => {
this.myRequests = JSON.stringify(data);
const requests = JSON.parse(this.myRequests);
this.Items = requests.filter(function(o) {
return o.detail;
});
},
err => {
console.log(err);
});
}
下面是从服务呼叫收到的响应:
Array [ {…}, {…} ] --> This is the array of object
0: Object { detail: {'id':'1', 'type': 'service1'} }
1: Object { detail: {'id':'2', 'type': 'service2'} }
以下是数组内容:
Array [ {…}, {…} ] --> This is the array of object
0: Object { detail: {'id':'1', 'type': 'service1'} }
1: Object { detail: {'id':'2', 'type': 'service2'} }
下面是HTML
<ul>
<li *ngFor="let each of Items">
{{each.request_id}}
</li>
</ul>
-
{{each.request_id}
访问detail.id
属性
<ul *ngFor="let each of Items">
{{each.detail.id}}
</ul>
{{each.detail.id}
访问detail.id
属性
<ul *ngFor="let each of Items">
{{each.detail.id}}
</ul>
{{each.detail.id}
尝试设置:返回o代码>
然后使用{{each.detail.id}
访问,尝试设置:返回o代码>
然后使用{{each.detail.id}
访问id
,使用以下命令
<ul *ngFor="let each of Items">
{{each.detail.id}}
</ul>
{{each.detail.id}
此外,您应该更喜欢并使用更多上下文名称,如项
来代替每个
,因为如果是长代码和嵌套的ngFor
,则上下文将丢失
要进行调整,要获得id
,请使用以下命令
<ul *ngFor="let each of Items">
{{each.detail.id}}
</ul>
{{each.detail.id}
此外,您应该更喜欢并使用更多上下文名称,如项
来代替每个
,因为如果是长代码和嵌套的ngFor
,则上下文将丢失
要进行调整,您可以使用post方法的通用版本,它允许您指定请求的响应类型
在您的情况下,响应格式似乎如下所示:
interface Response {
detail: Detail
}
interface Detail {
id: string;
type: string;
}
因此,您可以通过以下方式发出http请求:
this.http.post<Array<Response>>(
this.apiurl,
{'user': this.user}
// no need to specify responseType, json is default
)
.subscribe(data => {
// now data is of Response Type
this.Items = data.filter(item => item.detail);
});
this.http.post您可以使用的post方法的通用版本允许您指定请求的响应类型
在您的情况下,响应格式似乎如下所示:
interface Response {
detail: Detail
}
interface Detail {
id: string;
type: string;
}
因此,您可以通过以下方式发出http请求:
this.http.post<Array<Response>>(
this.apiurl,
{'user': this.user}
// no need to specify responseType, json is default
)
.subscribe(data => {
// now data is of Response Type
this.Items = data.filter(item => item.detail);
});
this.http.post你的问题是什么?你的问题是什么?