简体   繁体   中英

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.

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"]);

Use data observable on Activatedroute instead of snapshot.data. Then using rxjs pluck operator you can extract the desired data.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM