Angular asyn c канал с mergeMap - PullRequest
0 голосов
/ 20 июня 2020

Я экспериментирую.

В моем компоненте я вызываю API 9 раз и каждый раз извлекаю заголовок с помощью mergeMap. Затем я пытаюсь отобразить эти заголовки в своем шаблоне, но не удается сказать, что ngFor не поддерживает строку, а только массивы.

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>

Ответы [ 2 ]

0 голосов
/ 20 июня 2020

Похоже, что ваши наблюдаемые возвращаются в виде строки для каждого элемента, что вы можете сделать, это использовать оператор 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

0 голосов
/ 20 июня 2020

Измените заголовок на: -

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"))
  ))
...