簡體   English   中英

如何將解析器返回的數據合並到 combineLatest 調用中?

[英]How to combine data returned by a resolver into a combineLatest call?

我在頁面上有一個解析器來加載數據。 這個解析器返回一個Observable<Product[]>

然后我使用 combineLatest 將來自解析器的流與另一個流合並。

但問題是當我組合流時,我收到一個錯誤,說我的流在初始化之前就被使用了。 我嘗試將 combineLatest 放入一個函數中,並在從解析器獲取數據后調用它。 然后我在 combineLatest 中的 products.filter 調用中收到一條錯誤消息“過濾器不是函數”。

categorySelectedSubject = new Subject<number>();
categorySelectedAction$ = this.categorySelectedSubject.asObservable();

ngOnInit(): void {
  this.productsWithCategoriesResolved$ = this.route.snapshot.data["resolvedData"]
}

this.filteredByCategoryProducts$ = combineLatest([
      this.productsWithCategoriesResolved$,
      this.categorySelectedAction$
        .pipe(
          startWith(0)
        )
    ])
    .pipe(
      map(([products, selectedCategoryId]) =>
        products.filter(p => selectedCategoryId ? p.categoryId === selectedCategoryId : true)
      ),
      catchError(err => {
        this.errorMessage = err;
        return EMPTY;
      })
    );

 onCategorySelected(categoryId: string){
    this.categorySelectedSubject.next(+categoryId)
  }

非常感謝您的任何幫助或建議。

combineLatest運算符需要所有可觀察對象,並且當所有可觀察對象發出值至少為 1 時,它就會調用 subscribe。 在這里,您有this.route.snapshot.data["resolvedData"]持有產品集合( Product[] )。

你必須轉換filteredByCategoryProducts$持有的可觀察的Product[]剛剛加入of運營商轉換流。

import { combineLatest, of } from 'rxjs';

this.filteredByCategoryProducts$ = of(this.route.snapshot.data["resolvedData"]);

使用 Activatedroute 上可觀察到的數據而不是 snapshot.data。 然后使用 rxjs pluck operator 您可以提取所需的數據。

this.productsWithCategoriesResolved$ = this.route.data.pipe(pluck('resolvedData'));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM