我希望*ngFor
遍历通过异步管道提供的http.get
的结果。项目未呈现,加载div 也未呈现。
服务:
public getKeywords = () => {
return this.http.get<getKeywords>(`${this.uri}/keywords`);
}
接口:
interface getKeywords {
keywords: Array<object>;
}
TS:
export class KeywordsSettingsComponent implements OnInit {
public currentKeywords$: any;
constructor(private profileProvider: ProfileProvider) { }
ngOnInit() {
this.currentKeywords$ =
this.profileProvider.getKeywords().pipe(map(({ keywords }) => keywords));
}
}
模板:
<div class="row">
<ng-template *ngIf="currentKeywords$ | async as currentKeywords ; else loading">
<div class="keyword" * ngFor="let keywordObj of currentKeywords">
{{ keywordObj.keyword }}
<span class="icon-close"> </span>
</div>
</ng-template>
<ng-template #loading> Loading keywords...</ng-template>
</div>
加载div 未显示的事实表示未发出值。如果我像这样订阅 ngOnInt:
this.currentKeywords$ = this.profileProvider.getKeywords().pipe(map(({keywords}) => keywords), share()).subscribe(res => res));
加载div 确实显示,但结果不会呈现在*ngFor
div 中。但是,我知道异步管道管理订阅/取消订阅,因此在ngOnInit中订阅应该是不必要的。
来自 http.get 的结果:HTTP 调用返回一个具有多个属性的对象,其中一个是包含对象数组的"关键字"。我正在使用map((来映射到单个属性并访问对象数组。
{..."keywords":[{"id":331,"keyword":"spam"},{"id":330,"keyword":"foo"},{"id":332,"keyword":"brexit"}]}
基于HTTP返回一个对象的事实,您需要更改以下内容:
<div class="keyword" * ngFor="let keywordObj of currentKeywords">
对此:
<div class="keyword" *ngFor="let keywordObj of currentKeywords.keywords">
我也会改变这个:
this.currentKeywords$ =
this.profileProvider.getKeywords().pipe(map(({ keywords }) => keywords));
对此也是如此:
this.currentKeywords$ = this.profileProvider.getKeywords();
。因为那张地图并没有真正映射任何东西。
您可能还需要将第一个<ng-template
更改为例如 <div
,因为我想它不会自行渲染。
希望对您有所帮助。