canActivate不会响应订阅更改Angular 2 Router AngularFire2 [英] canActivate doesn't respond upon subscription change Angular 2 Router AngularFire2
问题描述
我正在使用AngularFire2.这就是我接触AuthGuard
服务的方式:
I'm using AngularFire2. This is how I approached my AuthGuard
service:
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后,它不会加载相应的组件.
The above code works, except when I visit a guarded page directly (i enter URL in browser), it doesn't load the respective component after the subscription resolves to true.
在角度1中,守护路线是为了确保在路线甚至加载之前先解决一些问题.
In angular 1, guarding the route was ensuring something resolves first before the route even loads.
它显示在角度2中,路由加载(无论是真还是假,并且不等待来自网络的任何响应),因此,当订阅值恢复为true时,我必须转到另一条路由,然后在它起作用之前回来.
It appears in angular 2, the route loads (whether true or false, and doesn't wait for any response from the wire), therefore by the time the subscription value returns as true, I have to go to another route, then come back before it works.
在Angular 2中保护我的路线响应的正确方法是什么?
What is the proper way to guard my route to be responsive in Angular 2?
推荐答案
在您的代码中,在执行传递给this.af.auth.subscribe(...)
的回调函数之前,先执行return this.allowed;
.
In your code return this.allowed;
is executed before the callback function passed to this.af.auth.subscribe(...)
is executed.
应该像
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()
}
这篇关于canActivate不会响应订阅更改Angular 2 Router AngularFire2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!