2017-10-09 2 views
0

각도 4를 사용하고 있는데이 경로가 변경되어 페이지를 다시로드해야하는 구성 요소 중 하나에 코드가 있습니다.각도 : 단일 경로를 변경하면 여러 'NavigationEnd'이벤트가 발생합니다.

ngOnInit() { 
     this.router.events.subscribe((value) => { 
      if (value instanceof NavigationEnd) { 
      console.log(value); 
      } 
     }); 
    } 

내 문제는 내가 한 경로에 대해 여러 'NavigationEnd'이벤트를 얻을 수 있다는 것입니다. 일부 route console.log의 경우에도 6,7 값을 씁니다.

어떻게 될 수 있습니까?

답변

1

"리로드 페이지"란 navigate 메서드를 this.router이라고 부르는 것을 의미합니다. 이 경우는이 구성 요소의 인스턴스를 만들 때마다 라우터 이벤트의 새 관찰자를 만들지 만 생성 된 subscriptionngOnDestroy주기에 처리하지 않는 것이 가장 관련이 있습니다. 이 문제를 해결하려면 다음을 수행하십시오.

import { Subscription } from 'rxjs/Subscription'; 
import 'rxjs/add/operator/do'; 
import 'rxjs/add/operator/filter';  

export class FooComponent implements OnInit, OnDestroy { 
    private _routerSub = Subscription.EMPTY; 
    constructor(private router: Router){} 

    ngOnInit(){ 
    this._routerSub = this.router.events 
     .filter(event => event instanceof NavigationEnd) 
     .do(event => console.log(value)) // use do operator for log operations 
     .subscribe((value) => { 
      //do something with the value 
     }); 
    } 

    ngOnDestroy(){ 
    this._routerSub.unsubscribe(); 
    } 
} 
+0

신속한 응답에 감사드립니다. 그것은 내 문제 였고, 나는 'ngOnDestroy'에서 탈퇴 이벤트를 파괴하지 않았다. 내가 그렇게해야한다는 것을 몰랐다. :) – Milos