Angular: Proper time to unsubscribe

后端 未结 3 779
清歌不尽
清歌不尽 2021-01-25 20:44

When using web services, when is the best time to unsubscribe? In my code I have been doing this

tempFunction() {
    const temp = this.myService.getById(id).sub         


        
3条回答
  •  渐次进展
    2021-01-25 21:28

    You don't need to unsubscribe from a simple web request like you have. They only fire once and will take care of the unsubscribe for you. Here is a SO question that discusses this very topic and why it is unnecessary.

    As a general topic of how to unsubscribe, the best approach tends to be using this pattern of using takeUntil. This allows you to ensure that everything is cleaned up when your component is destroyed in the cleanest way possible (without having to hold onto multiple subscriptions and calling unsubscribe on each of them).

    import { Subject } from 'rxjs/Subject';
    import 'rxjs/add/operator/takeUntil';
    
    @Component({ ... })
    export class ExampleComponent implements OnInit, OnDestroy {
        destroy$: Subject = new Subject();
    
        ngOnInit() {
            this.someMethodThatReturnsObservable(...)
                .takeUntil(this.destroy$)
                .subscribe(...);
    
            this.someOtherMethodThatReturnsObservable(...)
                .takeUntil(this.destroy$)
                .subscribe(...);
        }
    
        ngOnDestroy() {
            this.destroy$.next(true);
            // Now let's also unsubscribe from the subject itself:
            this.destroy$.unsubscribe();
        }
    }
    

提交回复
热议问题