ObjectUnsubscribedError when trying to prevent subscribing twice

前端 未结 2 1382
Happy的楠姐
Happy的楠姐 2020-12-05 04:18

I have a Service and a component that uses it:

  • PagesService
  • PagesListComponent

In the PagesService

2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-05 04:38

    I would get the subscription and unsubscribe on it this way and not on the subject directly:

    ngOnInit() {
      this.pages$ = this.pagesService.getPagesListener();
      this.subscription = this.pages$.subscribe((pages) => { // <-------
        this.pages = pages; console.log(pages);
      });
      this.pagesService.getAll();
    }
    
    ngOnDestroy() {
        this.subscription.unsubscribe(); // <-------
    }
    

提交回复
热议问题