2016-09-25 50 views
2

我正在使用AngularFire2。这是我走近我AuthGuard服务:canActivate在订阅更改时不作出响应Angular 2路由器AngularFire2

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),认购解析后,它不会加载相应组件真正。

在angular 1中,守护路线确保在路线加载之前先解决某个问题。

它出现在第2角度,路由负载(无论是真还是假,并且不等待来自线路的任何响应),因此,当订阅值返回为真时,我必须去另一条路由,然后在它工作之前回来。

什么是正确的方法来保护我的路线,以响应Angular 2?

回答

4

在您的代码return this.allowed;执行之前执行回调函数传递给。

应该是这样

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() 
    } 
+0

与错误回来:'属性“地图”在'AngularFireAuth'类型上不存在。' – Rexford

+0

你必须导入'map'。在没有'ßAngularDireAuth''的情况下搜索你的错误消息 –

+0

即使这样,在导入'map'之后,我得到这个错误: '错误TS2322:类型'Observable '不能分配给'boolean'类型。' – Rexford

1

如果您过来找角4 angularfire 4,这个我怎么调整冈特的回答是:

canActivate(route: ActivatedRouteSnapshot):Observable<boolean>{ 
    return this.af.authState.map((user)=>{ 
     if(user != null){ 
     return true; 
     }else{ 
     this._store.dispatch(new LayoutOpenLoginAction()); 
     return false; 
     } 
    }).first(); 
    } 
+0

感谢您的更新。事情进展得如此之快,难以跟上。 – Rexford