본문 바로가기
Angular.js

ActivatedRoute의 snapshot과 Router의 events의 다른 점.

by 찬찬2 2023. 11. 15.

ActivatedRouted의 snapshot은 컴포넌트가 생선된 바로 그 순간의 URL정보를 받아온다.

 

만약 URL이 동적으로 변한다면, Router의 events를 활용해야 한다.

 

events에서는 많은 정보들을 제공한다. 이때 RxJS의 pipe와 filter 연산자로 특정 (프로퍼티/인스턴스)를 찾아내야 한다.

 

여기서 내가 필요한 것(프로퍼티/인스턴스)은 라우팅이 종료된 시점의 URL이다. 바로 "NavigationEnd" 이다.

 

아래 코드를 참고하자.

 

다른 라우터 이벤트 종류 보기

 

  NavigationStart
  NavigationEnd

    NavigationStart = 0,
    NavigationEnd = 1,
    NavigationCancel = 2,
    NavigationError = 3,
    RoutesRecognized = 4,
    ResolveStart = 5,
    ResolveEnd = 6,
    GuardsCheckStart = 7,
    GuardsCheckEnd = 8,
    RouteConfigLoadStart = 9,
    RouteConfigLoadEnd = 10,
    ChildActivationStart = 11,
    ChildActivationEnd = 12,
    ActivationStart = 13,
    ActivationEnd = 14,
    Scroll = 15,
    NavigationSkipped = 16
  NavigationCancel
  NavigationError
  RoutesRecognized
  ResolveStart
  ResolveEnd
  GuardsCheckStart
  GuardsCheckEnd
  RouteConfigLoadStart
  RouteConfigLoadEnd
  ChildActivationStart
  ChildActivationEnd
  ActivationStart
  ActivationEnd
  Scroll
  NavigationSkipped

 

export class YourComponent implements OnInit {
  currentUrl: string;

  constructor(private route: ActivatedRoute, private router: Router) {}

  ngOnInit() {
    // Subscribe to route changes to update the current URL dynamically
    this.router.events.pipe(filter(event => event instanceof NavigationEnd)).subscribe((result) => {
      this.currentUrl = this.route.snapshot.url.join('/');
      //또는 result에서 url 프로퍼티로 확인할 수 있다.
    });
  }
}

 

댓글