Kho*_*Phi 2 angular2-routing angular2-services angularfire2 angular
我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
上面的代码有效,除非我直接访问受保护的页面(我在浏览器中输入URL),它在订阅解析为true后不会加载相应的组件.
在角度1中,保护路线是确保在路线加载之前先解决某些事情.
它出现在角度2中,路由加载(无论是真还是假,并且不等待来自线路的任何响应),因此当订阅值返回为真时,我必须转到另一条路线,然后返回在它工作之前.
什么是保护我的路线在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()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1337 次 |
| 最近记录: |