我是否必须取消订阅 ActivatedRoute(例如 params)可观察量?

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

我发现很多例子,其中 ActivatedRoute Observable 像 paramsurl 被订阅但没有取消订阅。

constructor(private route: ActivatedRoute) {}

ngOnInit() {
  this.route.params
    // (+) converts string 'id' to a number
    .switchMap((params: Params) => this.service.getHero(+params['id']))
    .subscribe((hero: Hero) => this.hero = hero);
}

当路由器导航到不同的路由时,组件将被销毁并且 routerState 将变为未引用,这将使它们可以自由地收集垃圾,包括可观察的。

如果您将对该组件的引用传递给其他组件或服务,该组件将不会被垃圾收集并且订阅将保持活动状态,但我确信(无需验证)可观察对象将完成在离开时被路由器触发并导致订阅取消。

没有

From the docs :

订阅组件中的可观察对象时,您几乎总是安排在组件销毁时取消订阅。

有一些 没有必要的特殊观察结果。 ActivatedRoute observables 属于例外.

A​​ctivatedRoute 及其可观察对象与路由器本身隔离。路由器在不再需要路由组件时销毁路由组件,注入的 ActivatedRoute 随之消失。

请随时退订。这是无害的,绝不是一种坏习惯。

如中奖答案quotessubscriptionsActivatedRoute,Angular自动unsubscribes

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

如果您想知道如何 unsubscribeObservables:

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 = this.activatedRoute.params.subscribe( params => {

    });
  }

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

}

无论何时向组件添加订阅,您几乎总是需要在组件被销毁时取消订阅。但是订阅 Activated 路由参数不需要取消订阅,因为路由器会在不再需要时销毁订阅。

Http observables 调用和路由器 observables 不需要手动取消订阅。如果您处理其他类型的可观察对象或您自己的可观察对象,您应该在 ngOnDestroy() 上进行。您可以在 Suscription 对象中调用 unsubscribe() 方法,在该对象中将可观察对象存储在组件中。