简体   繁体   中英

How to move subscription logic from ngOnInit to ngOnChange

This is a more generell question regarding Angular - which I am pretty new to - being a React-nerd all-through.

I have a task to move logic to ngOnChanges covering each cases when we should subscribe, keep the existing subsciption or unsubscribe. How do I do that?

This is some example code:

ngOnInit() {

    const obsValue$ = combineLatest([
        this.store.pipe(select(this.example1Selector.getData())),
        this.store.pipe(select(this.example2Selector.getData()))
    ]).pipe(
        tap(([important1, important2]) => {
            this.important1 = important1;
            this.important2 = important2;
        })
    );
}

I want to move this code to the ngOnChange and subscribe to in only when needed and keep it when necessary and unsubscribe when necessary. How do I do that?

You should unsubscribe subscriptions you don't longer need either by calling Subscription#unsubscribe (requires you to save Subscriptions ) or by ending event stream with Subject#complete which finalizes all subscriptions - but that is not always applicable.

Failing to do so can lead to resource leaks. (that depends on actual observable and if it is closed as some point or not)

Also I usually unsubscribe/complete in ngOnDestroy lifecycle hook as well.

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