codememo

Angular2 경로 변경 주의사항

tipmemo 2023. 6. 12. 21:32
반응형

Angular2 경로 변경 주의사항

@RouteConfig([
    {path: '/about', name: 'About', component: About, useAsDefault: true},
    {path: '/test', name: 'Test', component: Test}
])

export class MyApp {
    router: Router;
    location: Location;
    isCollapsed: boolean = true;

    // ON ROUTE CHANGE {
        this.isCollapsed = true;
    // }

    constructor(router: Router, location: Location) {
        this.router = router;
        this.location = location;
    }
}

모든 경로 변경 시 변수 값을 변경해야 하는데, Angular 2.x에서 이 이벤트를 어떻게 볼 수 있습니까?

Angular의 최종 버전(예: Angular 2/4)에서는 다음을 수행할 수 있습니다.

this.router.events.subscribe((event) => {
    if(event.url) {
        console.log(event.url);
    }
});

경로가 바뀔 때마다events관찰 가능한 정보가 있습니다.문서를 보려면 여기를 클릭하십시오.

사용 중인 경우

"@angular/router": "3.0.0-alpha.7", 
"@angular/router-deprecated": "2.0.0-rc.2",

그리고나서

this.router.events.subscribe((event) => {
      console.log('route changed');
});

여기 제 앱에서 사용하는 것이 있습니다.경로 인스턴스에 가입하여 변경 사항을 추적할 수 있습니다.

class MyClass {
  constructor(private router: Router) {
    router.subscribe((val) => /*detect changes*/)
  }
}

이벤트는 관찰할 수 있으므로 구독할 수 있습니다, 저는 앵글5에서 성공적으로 시도했습니다.

this.router.events.subscribe((event) => {
console.log(event);
 if(event['url'] && event['url'] == '/') {
    console.log('Home page');
    //any other functionality you can do here
 }
});

경로가 변경될 때 이벤트를 포착하고 jQuery와 같은 일부 코드를 초기화하려면 다음을 사용합니다.OnActive후크. 예:

import {Component} from 'angular2/core';
import {OnActivate,ComponentInstruction} from "angular2/router";
declare var $:any;
declare var Foundation:any;
@Component({
templateUrl :'/app/templates/home.html'
})
export class HomeComponent implements OnActivate{

  routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction)
  {

    new Foundation.Orbit($("#es-slide-show"), {});
    return true;
  }
}

이것이 가장 좋은 방법입니다.

import { NavigationEnd, Router, RouterEvent } from '@angular/router'

constructor(private router: Router) {}

ngOnInit(): void {
  this.router.events.pipe(
    filter((evt: RouterEvent) => evt instanceof NavigationEnd)
  ).subscribe((evt: RouterEvent) => {
    // with the above filter, both the following will always log the same url
    console.log(evt.url)
    console.log(this.router.url)
  })
}

언급URL : https://stackoverflow.com/questions/34444822/angular2-watch-for-route-change

반응형