我正在寻找一种访问已加载路由的方法。
最初,路由更改可以通过路由器事件订阅,如下所示:
@Directive({ selector: '[myDirective]' })
export class TestDirective {
constructor(private _router: Router) {
this.doAction()
}
doAction(): void {
this._router.events
.filter((event: Event) => event instanceof NavigationEnd)
.subscribe(event => {
/// ... get current route data
})
}
}
}
主要问题是如何在subscribe()中获取当前的路由数据???
在 Angular 2 文档中,搜索未找到结果。
最佳答案
我有一个解决方案可以解决您的问题,请尝试一下。
import { Router, ActivatedRoute } from '@angular/router';
currentRoute:any;
constructor(private router: Router, private activatedRoute: ActivatedRoute,) {}
ngOnInit() {
this.router.events.subscribe((url) => {
this.currentRoute = url;
console.log(this.currentRoute);
});
}
从查询参数中获取值
import { Router, Route, ActivatedRoute } from '@angular/router';
queryParams:string;
constructor(private router: Router, private actRoute: ActivatedRoute)
{
this.queryParams=
this.router.routerState.snapshot.root.queryParams["oauth_token"];
}
使用它,您将获得 queryParams 的 oauth_token 值。我认为这对你来说似乎不错
注意:您的网址将类似于 http://example.com?oauth_token=123
关于angular - 如何通过 angular2 指令中的选项获取当前路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40306334/