在我的 AppComponent 中,我正在进行启动检查。如果应用程序是使用具有 sessionId 的查询字符串打开的,那么我们就可以开始了,我想将它们路由到/application 路径。否则我希望他们导航到/create-session 路径。问题是,在应用程序看到查询参数之前,params 订阅会触发一次,这意味着 else 语句始终会被触发,并且用户会自动重定向到创建 session 路径。
this.route.queryParams.subscribe(params => {
if(params.sid) {
this.ngRedux.dispatch(this.sessionActions.setSessionId(params.sid));
this.router.navigate(['application'])
}
else{
this.router.navigate(['create-session'])
}
})
我尝试做一些事情来过滤掉没有任何数据的订阅,如下所示:
.first((val, idx, src)=> Object.keys(val).length > 0)
但是当没有查询参数时它不会触发。 有没有一种方法可以立即获取参数快照而不需要订阅ActivatedRoute?
注意:此订阅发生在 ngOnInit
最佳答案
您可以使用 guards 来实现此功能在 Angular 。
创建一个这样的守卫:
@Injectable()
export class SomeGuard implements CanActivate {
constructor(
private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot) {
console.log('state params', state.root.queryParams);
if (state.root.queryParams.sid){
this.router.navigate(['application'])
} else {
this.router.navigate(['create-session'])
}
return false;
}
}
然后将守卫添加到要执行此逻辑的路由上的 canActivate 中:
export const routes: Routes = [
{
path: '**',
component: SomeComponent,
canActivate: [SomeGuard]
}
];
不要忘记在您的提供程序中添加防护:
@NgModule({
providers: [SomeGuard]
})
关于javascript - 立即访问 Angular 4 查询参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44272681/