Home > database >  Typescript observable not updating
Typescript observable not updating

Time:10-18

ngOnInit(): void {
          this.currentProductService.getCode().subscribe(code => {
            if (code) {
              this.crumbs$ = this.breadCrumbsService.getBreadCrumbsForProductPage(code)
                  .map(data => {
                    return data.breadCrumbs;
                  }));
            }
}

Hi,

I'm trying to set "this.crumbs" which is an observable of object []. This works fine on the initial page load. But when I navigate this value isn't getting updated when a new 'code' is been fetched through the subscribe method.

Does anyone know any solution or tips??

CodePudding user response:

You don't subscribe to the 2nd observable, switchMap will fix that.

class Foo {
  ngOnInit(): void {
    this.currentProductService.getCode()
      .pipe(
        switchMap((code) => {
          return this.breadCrumbsService.getBreadCrumbsForProductPage(code)
        }))
      .subscribe(data => {
        // do what you want with data.breadCrumbs;
      })
  }
}
  • Related