[英]Angular async pipe with mergeMap
I am experimenting.我正在试验。
In my component I call an API 9 times and each time extract the title with a mergeMap.在我的组件中,我调用 API 9 次,每次都使用 mergeMap 提取标题。 I then try to display those titles in my template, but it fails saying ngFor doesn't support string, only arrays.然后我尝试在我的模板中显示这些标题,但它没有说 ngFor 不支持字符串,只支持 arrays。
titles$: Observable<string[]>;
ngOnInit(): void {
this.titles$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9).pipe(
mergeMap<number, any>((x) => ajax.getJSON(this.apiUrl + x)),
mergeMap<Person, any>((person) => of(person?.title ?? "bad"))
) as Observable<string[]>;
}
//This nicely prints out the titles
this.titles$.subscribe((title) => console.log(title));
<div *ngIf="titles$">
<div *ngFor="let title of titles$ | async">
{{ title }}
</div>
</div>
Change your title statement to:-将您的标题声明更改为:-
this.titles$ = forkJoin(of(1, 2, 3, 4, 5, 6, 7, 8, 9).pipe(
mergeMap<number, any>((x) => ajax.getJSON(this.apiUrl + x)).pipe(map<Person, any>((person) => person?.title ?? "bad"))
))
Seems like your observables return back as a string for each items, what you could do is use the toArray()
operator.似乎您的可观察对象作为每个项目的字符串返回,您可以做的是使用toArray()
运算符。
this.titles$ = of(1, 2, 3, 4, 5, 6, 7, 8, 9).pipe(
mergeMap<number, any>((x) => ajax.getJSON(this.apiUrl + x)),
mergeMap<Person, any>((person) => of(person?.title ?? "bad")),
toArray()
) as Observable<string[]>;
StackBlitz: https://stackblitz.com/edit/angular-ivy-vcprxo StackBlitz: https://stackblitz.com/edit/angular-ivy-vcprxo
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.