这个问题在这里已有答案:
我正在尝试在我的Web应用程序中获取当前的URL或路由,我想出了在angular中使用以下代码执行此操作的方法
```
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class IncService {
public mainPage: any;
constructor(private router: Router) {
//get current route
router.events.subscribe(endUrl => {
if(endUrl instanceof NavigationEnd ){
this.mainPage = endUrl.url;
console.log(this.mainPage); //works perfectly
}
});
console.log(this.mainPage); //does not work, outputs undefined
}
}
```
我希望console.log(this.mainPage)输出当前路由,例如/ home,但我得到'undefined'。
NB我希望'this.mainPage'在我班级的任何地方都可以作为当前的URL而不仅仅是在subscribe()中
你可以移动console.log(this.mainPage);
来完成这样的() =>{}
,你不能在课堂上的任何地方使用,因为订阅称为asynchronous
。
//get current route
router.events.subscribe(endUrl => {
if(endUrl instanceof NavigationEnd ){
this.mainPage = endUrl.url;
console.log(this.mainPage); //works perfectly
}
},
()=>{
console.log(this.mainPage); //does not work, outputs undefined
});
}