[英]How do I get the data from my component into html in Angular before the page gets displayed?
我正在尝试显示从组件中的api检索到的值。 当API用数据响应时,将显示我的页面,并且我永远无法显示元素列表。 您能告诉我如何解决此问题并在html页面中显示值吗?
这是我的api调用
public searchTeamInfo(term: string): Observable<TeamInfo> {
return this.http.get<TeamInfo>(`/api/${term}`);
}
我正在组件中调用api。
public associatedPodNames: Array<TeamInfo>;
associatedTeamIds: [
"12345",
"45454",
"43543543"
]
ngOnInit() {
this.getTeamInfo();
}
public getTeamInfo(): Array<IPodDetails> {
for (let i = 0; i < this.associatedTeamIds.length; i++) {
this.searchService.searchTeamInfo(this.associatedTeamIds[i]).subscribe(res => {
this.associatedPodNames.push(res);
console.log(this.associatedPodNames);
},
);
}
}
我正在尝试使用以下代码在html页面中显示值。
<ng-container *ngFor="let pods of associatedPodNames">
pods
</ng-container>
我可以在控制台中看到关联的PodNames列表的结果。 这是示例结果。
[{podId: "12345", podName: "sample1", podType: "Project Pod"},
{podId: "45454"podName: "sample2"podType: "Project Pod"},
{podId: "43543543", podName: "sample3", podType: "Delivery Pod"}]
即使我在控制台中看到pod信息,associatedPodnames也显示为空。 我该如何解决?
如果要呈现结果,则需要使用JSON pipe
并且需要使用{{}}
来绑定数据。
JSON pipe
将在HTML上显示对象的整个结构,例如
<ng-container *ngFor="let pods of associatedPodNames">
{{pods | json}}
</ng-container>
要么
使用对象的属性:
<ng-container *ngFor="let pods of associatedPodNames">
{{pods.podId}}
</ng-container>
您可以使用要显示的对象内部要显示的任何属性。
Angular Docs https://angular.io/guide/displaying-data
仅供参考,有几种方法可以将数据绑定到HTML
属性绑定,事件绑定和双向数据绑定。
您需要使用像这样的双花括号:{{pods.property}}来绑定一种内容
你必须pods
指容器内的每个对象。 您需要在容器内使用一个角度表达式{{}}来显示输出值:
<ng-container *ngFor="let pods of associatedPodNames">
<p>{{pods.podName}}</p>
</ng-container>
associatedTeamIds: [
"12345",
"45454",
"43543543"
]
ngOnInit() {
this.getTeamInfo();
}
public getTeamInfo(): Array<IPodDetails> {
for (let i = 0; i < this.associatedTeamIds.length; i++) {
this.searchService.searchTeamInfo(this.associatedTeamIds[i]).subscribe(res => {
this.associatedPodNames = this.associatedPodNames.concat(res);
console.log(this.associatedPodNames);
},
);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.