我正在使用 AngularFire2。这就是我的方法AuthGuard
服务:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
this.af.auth.subscribe((auth) => {
if(auth == null) {
this.router.navigate(['/login']);
this.allowed = false;
} else {
this.allowed = true;
}
})
return this.allowed;
}
上面的代码有效,除了当我直接访问受保护的页面(我在浏览器中输入 URL)时,它在订阅解析为 true 后不会加载相应的组件。
在角度 1 中,保护路线就是确保在路线加载之前先解决某些问题。
它出现在角度 2 中,路由加载(无论 true 或 false,并且不等待来自线路的任何响应),因此当订阅值返回 true 时,我必须转到另一条路由,然后返回在它起作用之前。
保护我的路线以在 Angular 2 中做出响应的正确方法是什么?
在你的代码中return this.allowed;
在回调函数传递给之前执行this.af.auth.subscribe(...)
被执行。
应该是这样的
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/first';
import { Observable } from 'rxjs/Observable';
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
return this.af.auth.map((auth) => {
if(auth == null) {
this.router.navigate(['/login']);
return false;
} else {
return true;
}
}).first()
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)