Do I have to unsubscribe from ActivatedRoute (e.g. params) observables?

大憨熊 提交于 2019-11-28 07:58:20

From the docs :

When subscribing to an observable in a component, you almost always arrange to unsubscribe when the component is destroyed.

There are a few exceptional observables where this is not necessary. The ActivatedRoute observables are among the exceptions.

The ActivatedRoute and its observables are insulated from the Router itself. The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

Feel free to unsubscribe anyway. It is harmless and never a bad practice.

The component will be destroyed and the routerState will become unreferenced when the router navigates to a different route, which will make them free to get garbage collected including the observable.

If you pass around references to this component to other components or services, the component won't be garbage collected and the subscription would be kept active, but I'm sure (without verifying) that the observable will be completed by the router when navigating away and cause the subscription to cancel.

As the winning answer quotes about the subscriptions to ActivatedRoute, Angular unsubscribes automatically.

The Router destroys a routed component when it is no longer needed and the injected ActivatedRoute dies with it.

In case you want to know how to unsubscribe from Observables:

import { Component, 
         OnInit,
         OnDestroy }      from '@angular/core';
import { ActivatedRoute } from '@angular/router'; 
// Type
import { Subscription } from 'rxjs/Subscription';


@Component({
  selector: 'app-example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss']
})
export class ExampleComponent implements OnInit, OnDestroy {
  paramsSubscription : Subscription;

  constructor(private activatedRoute : ActivatedRoute) { }

  /* Angular lifecycle hooks
  */
  ngOnInit() {
    console.log("Component initialized");
    this.paramsSubscription = activatedRoute.params.subscribe( params => {

    });
  }

  ngOnDestroy() {
    console.log("Component will be destroyed");
    this.paramsSubscription.unsubscribe();
  }

}

Whenever you are adding subscribe to a component, you always almost need to unsubscribe when the component is getting destroyed. But subscribe to the Activated route params doesn't require to unsubscribe as the router destroys the subscribe whenever its no longer needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!