代码之家  ›  专栏  ›  技术社区  ›  danday74

有必要取消订阅。激活路由订阅

  •  1
  • danday74  · 技术社区  · 7 年前

    我的代码:

    ngOnInit() {
    
      this.activatedRoute.params.subscribe((params: Params) => {
        // do stuff
      })
    
      this.activatedRoute.data.subscribe((data: any) => {
        // do stuff
      })
    
    }
    

    作为一个习惯,我总是不明嫌犯,但不确定是否有必要在这里。

    4 回复  |  直到 7 年前
        1
  •  3
  •   Suren Srapyan    7 年前

    不,你不需要取消订阅路线观察

    Documentation

    当订阅组件中的可观测数据时,几乎总是 安排在组件被销毁时取消订阅。

    有一些特殊的观测数据是不必要的。 ActivatedRoute观测值属于例外情况。

    激活的路由及其可观测到的数据与路由器绝缘 本身。当路由组件不再是 需要,注入的激活路由也随之死亡。

    不管怎样,请随时退订。它是无害的,从不坏 练习。

        2
  •  2
  •   hamilton.lima    7 年前

    像这样的东西

      ngOnInit() {
        this.subscriptions.push(
          this.activatedRoute.params.subscribe((params: Params) => {
            // do stuff
          }));
    
        this.subscriptions.push(
          this.activatedRoute.data.subscribe((data: any) => {
            // do stuff
          }));
      }
    
      ngOnDestroy() {
        this.subscriptions.forEach((subscription: Subscription) => {
          subscription.unsubscribe();
        });
      }
    

    请看下面的示例: https://stackblitz.com/edit/angular-unsubscribing-then-all?file=src/app/app.component.ts

        3
  •  1
  •   penleychan    7 年前

    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.

    资料来源: Angular Doc

        4
  •  1
  •   Sachila Ranawaka    7 年前

    通常,当你的组件被破坏时,所有订阅的可观测数据都会自动取消订阅,只有少数例外。但activatedRoute不是其中之一。当路由器从路由组件中退出时,它将与注入的 activatedRoute