rxjs:结合可观察到的结果,同时已经使用异步管道显示了第一个

时间:2019-12-02 07:37:54

标签: angular rxjs rxjs-observables

使用rxjs进行角度显示时,最好的方法是显示第一个可观察对象的结果,并在其他可观察对象完成后合并数据?

示例:

@Component({
    selector: 'app-component',
    template: `
<div *ngFor="let group of groups$ | async">
    <div *ngFor="let thisItem of group.theseItems">
        ...
    </div>
    <div *ngFor="let thatItem of group.thoseItems">
        ...
    </div>
</div>
`
})
export class AppComponent implements OnInit {
    ...
    ngOnInit() {
        this.groups$ = this.http.get<IThisItem[]>('api/theseItems').pipe(
            map(theseItems => {
                return theseItems.groupBy('groupCode');
            })
        );

        // combine these results? This operation can take 5 seconds
        this.groups$$ = this.http.get<IThatItem[]>('api/thoseItems').pipe(
            map(thoseItems => {
                return thoseItems.groupBy('groupCode');
            })
        );
    }
}

我知道可以通过同时订阅和合并结果来完成。但是是否可以为此使用管道运算符并使用async管道?

3 个答案:

答案 0 :(得分:3)

我认为您可以使用combineLatest rxjs运算符。这可能意味着您也需要稍微更改模板中的处理方式。

我无法使用您的示例,因为我不知道您的get函数,但基本上适用相同的原理。

Check stackblitz here为例:

export class AppComponent  {

  private firstObservable = of([{name: 'name1'}]).pipe(startWith([]));
  private secondObservable = of([{name: 'name2'}]).pipe(startWith([]));

  combined = combineLatest(this.firstObservable, this.secondObservable).pipe(
        map(([firstResult, secondResult]) => {
          return [].concat(firstResult).concat(secondResult)
        }) 
   );
}

HTML输出:

<span *ngFor="let item of combined | async">{{item.name}}<span>

答案 1 :(得分:1)

Async pipe只是可观察的订阅者...要回答您的问题,您可以使用任何可能的方式...例如:

<div *ngFor="let group of groups$ | async as groups">
    <div *ngFor="let thisItem of group.theseItems">
        ...
    </div>
</div>

public groups$: Observable<type> = this.http.get<IThatItem[]>.pipe(
  startWith(INITIAL_VALUE)
);

public groups$: Observable<type> = combineLatest(
  of(INITIAL_VALUE),
  this.http.get<IThatItem[]>
)

答案 2 :(得分:1)

您可以使用合并和扫描。

  first$: Observable<Post[]> = this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts?userId=1');
  second$: Observable<Post[]>  = this.http.get<Post[]>('https://jsonplaceholder.typicode.com/posts?userId=2');
  combinedPosts$: Observable<Post[]> = merge(this.first$, this.second$).pipe(
    scan((acc: Post[], curr: Post[]) => [...acc, ...curr], [])
  )

https://www.learnrxjs.io/operators/combination/merge.html 使一个可以从许多中观察到。

https://www.learnrxjs.io/operators/transformation/scan.html 扫描类似于array.reduce ...您可以累积每个可观察到的发射的结果。

工作示例: https://stackblitz.com/edit/angular-lrwwxw

combineLatest运算符不太理想,因为它要求每个可观察对象在组合的可观察对象可以发射之前先发射:https://www.learnrxjs.io/operators/combination/combinelatest.html

  

请注意,直到每个可观察对象发出至少一个值时,combinateLatest才会发出初始值。

相关问题