简体   繁体   English

如何实现 Singleton 订阅 Angular 中的 router.events 9

[英]How Can I Achieve a Singleton Subscription To router.events in Angular 9

    constructor(
    private route: ActivatedRoute,
    private router: Router,
    private viewportScroller: ViewportScroller
  ) {
    this.router.events
      .pipe(filter((e): e is Scroll => e instanceof Scroll))
      .subscribe((e) => {
        if (e.position) {
          console.log("// position navigation", e.position);
          this.viewportScroller.scrollToPosition(e.position);
        } else if (e.anchor) {
          console.log("// anchor navigation", e.anchor);
          this.viewportScroller.scrollToAnchor(e.anchor);
        } else {
          console.log("// forward navigation");
        }
      });
  }

I have the code above (or equivalent) in an angular 9 component.我在 angular 9 组件中有上述代码(或等效代码)。 When I move back and forth in the application, coming to the component again and again using forward and back navigation, I notice that the subscriptions to router.events keep mounting up... Yet there is no way to unsubscribe from the router.events for instance inside of ngOnDestroy... How can I achieve a singleton event subscription in this case?当我在应用程序中来回移动,使用前进和后退导航一次又一次地来到组件时,我注意到对router.events的订阅不断增加......但是没有办法取消对router.events的订阅例如在 ngOnDestroy 内部......在这种情况下,如何实现 singleton 事件订阅?

An Observable doesn't have an unsubscribe method but a Subscription does . Observable 没有unsubscribe方法,但Subscription does When you call .subscribe on an Observable, it returns a Subscription object.当你在 Observable 上调用.subscribe时,它会返回一个Subscription object。 This is what we use to unsubscribe from our Observables.这是我们用来取消订阅我们的 Observables 的。

export class YourComponent implements OnDestroy {
    routerSubscription: Subscription;

    constructor(
    private route: ActivatedRoute,
    private router: Router,
    private viewportScroller: ViewportScroller
  ) {
    this.routerSubscription = this.router.events
      .pipe(filter((e): e is Scroll => e instanceof Scroll))
      .subscribe((e) => {
        if (e.position) {
          console.log("// position navigation", e.position);
          this.viewportScroller.scrollToPosition(e.position);
        } else if (e.anchor) {
          console.log("// anchor navigation", e.anchor);
          this.viewportScroller.scrollToAnchor(e.anchor);
        } else {
          console.log("// forward navigation");
        }
      });
  }

  ngOnDestroy() {
    if (this.routerSubscription) {
      this.routerSubscription.unsubscribe();
      this.routerSubscription = undefined; // just in case. If this.routerSubscription is undefined, calling .unsubscribe() on it will throw an error and halt your component
    }

  }
}

Above is a simple example.上面是一个简单的例子。 Hope this helps希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM