1- import { Component , Input , Inject , ElementRef , OnInit } from '@angular/core' ;
1+ import { Component , ElementRef , Inject , Input , OnInit } from '@angular/core' ;
22import { DOCUMENT } from '@angular/platform-browser' ;
3- import { Router , ActivatedRoute , NavigationEnd } from '@angular/router' ;
4- import { Observable } from 'rxjs/Observable' ;
5- import { Subscription } from 'rxjs/Subscription' ;
3+ import { ActivatedRoute , NavigationEnd , Router } from '@angular/router' ;
64import 'rxjs/add/observable/fromEvent' ;
75import 'rxjs/add/operator/debounceTime' ;
6+ import 'rxjs/add/operator/takeUntil' ;
7+ import { Observable } from 'rxjs/Observable' ;
8+ import { Subject } from 'rxjs/Subject' ;
89
910interface Link {
1011 /* id of the section*/
@@ -36,17 +37,15 @@ export class TableOfContents implements OnInit {
3637
3738 _rootUrl : string ;
3839 private _scrollContainer : any ;
39- private _scrollSubscription : Subscription ;
40- private _routeSubscription : Subscription ;
41- private _fragmentSubscription : Subscription ;
40+ private _destroyed = new Subject ( ) ;
4241 private _urlFragment = '' ;
4342
4443 constructor ( private _router : Router ,
4544 private _route : ActivatedRoute ,
4645 private _element : ElementRef ,
4746 @Inject ( DOCUMENT ) private _document : Document ) {
4847
49- this . _routeSubscription = this . _router . events . subscribe ( ( event ) => {
48+ this . _router . events . takeUntil ( this . _destroyed ) . subscribe ( ( event ) => {
5049 if ( event instanceof NavigationEnd ) {
5150 const rootUrl = _router . url . split ( '#' ) [ 0 ] ;
5251 if ( rootUrl !== this . _rootUrl ) {
@@ -56,7 +55,7 @@ export class TableOfContents implements OnInit {
5655 }
5756 } ) ;
5857
59- this . _fragmentSubscription = this . _route . fragment . subscribe ( fragment => {
58+ this . _route . fragment . takeUntil ( this . _destroyed ) . subscribe ( fragment => {
6059 this . _urlFragment = fragment ;
6160
6261 const target = document . getElementById ( this . _urlFragment ) ;
@@ -73,17 +72,15 @@ export class TableOfContents implements OnInit {
7372 this . _scrollContainer = this . container ?
7473 this . _document . querySelectorAll ( this . container ) [ 0 ] : window ;
7574
76- this . _scrollSubscription = Observable
77- . fromEvent ( this . _scrollContainer , 'scroll' )
75+ Observable . fromEvent ( this . _scrollContainer , 'scroll' )
76+ . takeUntil ( this . _destroyed )
7877 . debounceTime ( 10 )
7978 . subscribe ( ( ) => this . onScroll ( ) ) ;
8079 } ) ;
8180 }
8281
8382 ngOnDestroy ( ) : void {
84- this . _routeSubscription && this . _routeSubscription . unsubscribe ( ) ;
85- this . _scrollSubscription && this . _scrollSubscription . unsubscribe ( ) ;
86- this . _fragmentSubscription && this . _fragmentSubscription . unsubscribe ( ) ;
83+ this . _destroyed . next ( ) ;
8784 }
8885
8986 updateScrollPosition ( ) : void {
0 commit comments