Search code examples
angularrxjsobservableresolver

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


I have a resolver on a page to load the data. This resolver returns an Observable<Product[]>

Then I combine the stream from the resolver with another stream using combineLatest.

But the problem is when I combine the streams, I get an error that says my streams are used before being initialized. I tried to put the combineLatest into a function and call it after I got the data from the resolver. I then have an error message "filter is not a function" on the products.filter call in the combineLatest.

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)
  }

Thanks a lot for any help or suggestions.


Solution

  • combineLatest operator requires all observables, and when all observerables emit value at least one then it calls subscribe. Over here you have this.route.snapshot.data["resolvedData"] holding collection of products (Product[]).

    You have to convert filteredByCategoryProducts$ to hold an Observable of Product[] just by adding of operator to convert stream.

    import { combineLatest, of } from 'rxjs';
    
    this.filteredByCategoryProducts$ = of(this.route.snapshot.data["resolvedData"]);