Angular/RxJs When should I unsubscribe from `Subscription`

前端 未结 22 2303
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 04:56

When should I store the Subscription instances and invoke unsubscribe() during the NgOnDestroy life cycle and when can I simply ignore them?

22条回答
  •  一个人的身影
    2020-11-21 05:16

    I like the last two answers, but I experienced an issue if the the subclass referenced "this" in ngOnDestroy.

    I modified it to be this, and it looks like it resolved that issue.

    export abstract class BaseComponent implements OnDestroy {
        protected componentDestroyed$: Subject;
        constructor() {
            this.componentDestroyed$ = new Subject();
            let f = this.ngOnDestroy;
            this.ngOnDestroy = function()  {
                // without this I was getting an error if the subclass had
                // this.blah() in ngOnDestroy
                f.bind(this)();
                this.componentDestroyed$.next(true);
                this.componentDestroyed$.complete();
            };
        }
        /// placeholder of ngOnDestroy. no need to do super() call of extended class.
        ngOnDestroy() {}
    }
    

提交回复
热议问题