1
- import { Component , Input , Inject , ElementRef , OnInit } from '@angular/core' ;
1
+ import { Component , ElementRef , Inject , Input , OnInit } from '@angular/core' ;
2
2
import { 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' ;
6
4
import 'rxjs/add/observable/fromEvent' ;
7
5
import 'rxjs/add/operator/debounceTime' ;
6
+ import 'rxjs/add/operator/takeUntil' ;
7
+ import { Observable } from 'rxjs/Observable' ;
8
+ import { Subject } from 'rxjs/Subject' ;
8
9
9
10
interface Link {
10
11
/* id of the section*/
@@ -36,17 +37,15 @@ export class TableOfContents implements OnInit {
36
37
37
38
_rootUrl : string ;
38
39
private _scrollContainer : any ;
39
- private _scrollSubscription : Subscription ;
40
- private _routeSubscription : Subscription ;
41
- private _fragmentSubscription : Subscription ;
40
+ private _destroyed = new Subject ( ) ;
42
41
private _urlFragment = '' ;
43
42
44
43
constructor ( private _router : Router ,
45
44
private _route : ActivatedRoute ,
46
45
private _element : ElementRef ,
47
46
@Inject ( DOCUMENT ) private _document : Document ) {
48
47
49
- this . _routeSubscription = this . _router . events . subscribe ( ( event ) => {
48
+ this . _router . events . takeUntil ( this . _destroyed ) . subscribe ( ( event ) => {
50
49
if ( event instanceof NavigationEnd ) {
51
50
const rootUrl = _router . url . split ( '#' ) [ 0 ] ;
52
51
if ( rootUrl !== this . _rootUrl ) {
@@ -56,7 +55,7 @@ export class TableOfContents implements OnInit {
56
55
}
57
56
} ) ;
58
57
59
- this . _fragmentSubscription = this . _route . fragment . subscribe ( fragment => {
58
+ this . _route . fragment . takeUntil ( this . _destroyed ) . subscribe ( fragment => {
60
59
this . _urlFragment = fragment ;
61
60
62
61
const target = document . getElementById ( this . _urlFragment ) ;
@@ -73,17 +72,15 @@ export class TableOfContents implements OnInit {
73
72
this . _scrollContainer = this . container ?
74
73
this . _document . querySelectorAll ( this . container ) [ 0 ] : window ;
75
74
76
- this . _scrollSubscription = Observable
77
- . fromEvent ( this . _scrollContainer , 'scroll' )
75
+ Observable . fromEvent ( this . _scrollContainer , 'scroll' )
76
+ . takeUntil ( this . _destroyed )
78
77
. debounceTime ( 10 )
79
78
. subscribe ( ( ) => this . onScroll ( ) ) ;
80
79
} ) ;
81
80
}
82
81
83
82
ngOnDestroy ( ) : void {
84
- this . _routeSubscription && this . _routeSubscription . unsubscribe ( ) ;
85
- this . _scrollSubscription && this . _scrollSubscription . unsubscribe ( ) ;
86
- this . _fragmentSubscription && this . _fragmentSubscription . unsubscribe ( ) ;
83
+ this . _destroyed . next ( ) ;
87
84
}
88
85
89
86
updateScrollPosition ( ) : void {
0 commit comments