반응형
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
반응형
'codememo' 카테고리의 다른 글
| 인덱스 및 개체 유형이 아닌 Pandas DataFrame에서 값을 가져오는 방법 (0) | 2023.06.12 |
|---|---|
| VueJS + VUEX - 데이터 전송 관련 문제 (0) | 2023.06.12 |
| AVAudioPlayer가 디버그 모드에서 중단점을 던집니다. (0) | 2023.06.12 |
| 고객이 WooCommerce를 사용하여 구매할 때 MailChimp 그룹에 고객 청구 정보를 추가하려면 어떻게 해야 합니까? (0) | 2023.06.12 |
| 동등한 Postgre는 무엇입니까?Oracle의 CONNECT BY ... 시작 위치에 대한 SQL 구문? (0) | 2023.06.12 |