Angular: Proper time to unsubscribe

后端 未结 3 664
清歌不尽
清歌不尽 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:27

    The answer is: Unsubscribe when you are done with the subscription. If it needs to be active for the entire life of your component, then unsubscribing in ngOnDestroy is appropriate. If you only need one output from the observable, then unsubscribing in the .subscribe() callback makes sense. If some other condition in your app can mean the subscription is no longer needed at some arbitrary time, feel free to unsubscribe whenever needed.

    The only rule is "Don't forget to unsubscribe." There's no hard rule about when to do it.

提交回复
热议问题