我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
我正在寻找在我的AppComponent中检测路由变化。
然后,我将检查全局用户令牌,以查看用户是否已登录,以便在用户未登录时重定向该用户。
当前回答
以以下方式捕获路由更改事件…
import { Component, OnInit, Output, ViewChild } from "@angular/core";
import { Router, NavigationStart, NavigationEnd, Event as NavigationEvent } from '@angular/router';
@Component({
selector: "my-app",
templateUrl: "app/app.component.html",
styleUrls: ["app/app.component.css"]
})
export class AppComponent {
constructor(private cacheComponentObj: CacheComponent,
private router: Router) {
/* Route event types
NavigationEnd
NavigationCancel
NavigationError
RoutesRecognized
*/
router.events.forEach((event: NavigationEvent) => {
//Before Navigation
if (event instanceof NavigationStart) {
switch (event.url) {
case "/app/home":
{
//Do Work
break;
}
case "/app/About":
{
//Do Work
break;
}
}
}
//After Navigation
if (event instanceof NavigationEnd) {
switch (event.url) {
case "/app/home":
{
//Do Work
break;
}
case "/app/About":
{
//Do Work
break;
}
}
}
});
}
}
其他回答
角4。X及以上:
这可以通过使用ActivatedRoute类的url属性来实现,如下所示:
this.activatedRoute.url.subscribe(url =>{
console.log(url);
});
注意: 你需要从angular/router包中导入和注入提供商
import { ActivatedRoute } from '@angular/router`
and
constructor(private activatedRoute : ActivatedRoute){ }
我从RC 5开始这样做
this.router.events
.map( event => event instanceof NavigationStart )
.subscribe( () => {
// TODO
} );
位置的作品……
import {Component, OnInit} from '@angular/core';
import {Location} from '@angular/common';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private location: Location) {
this.location.onUrlChange(x => this.urlChange(x));
}
ngOnInit(): void {}
urlChange(x) {
console.log(x);
}
}
我是这么说的:
class ClassName {
constructor(private router: Router) {
router.events.subscribe((value) => {
// see this
console.log(value instanceof NavigationEnd)
});
}
}
路由器3.0.0-beta。2应该是
this.router.events.subscribe(path => {
console.log('path = ', path);
});