Angular获取当前路线定义,而不是未定义



我有此代码:

import { Router } from '@angular/router';

然后:

constructor(router: Router) {
    console.log(this.router.url);
}

当我加载页面时,它将首先告诉我URL为"/"

Unhandled Promise rejection: Error in ./BaPageTop class BaPageTop - inline template:22:4 caused by: Cannot read property 'url' of undefined ;

我想检查当前URL是否等于/login,否则将当前的URL重定向到构造函数中的"/login"。我尝试使用window.location.href执行此操作,但由于URL没有更改的可能性,但它不起作用?

基于构造函数代码,您永远不会将this.router设置为任何东西,因此它始终是undefined。默认情况下,当您将参数传递到构造函数时,它不会成为this的属性。您应该将代码更改为:

constructor(router: Router) {
    console.log(router.url);
}

另外,如果您真的想使用this.router(例如,如果要在同一类中使用其他功能中的路由器),则可以在声明参数时使用publicprivate关键字:

constructor(private router: Router) {
    console.log(this.router.url);
}

最新更新