我试图在angularfire(2.0.0-rc.4)(由angular cli创建)中编写一个路由器保护程序,它等待angularfire(2.0.0-beta.2)检查登录状态,并在允许用户进入该状态之前(匿名)登录用户。
我的警戒代码是:
canActivate() {
/* This part is to detect auth changes and log user in anonymously */
this.auth
.subscribe(auth => {
if (!auth) {
this.auth.login();
}
});
/* This part is to listen to auth changes and IF there is an auth, resolves this guard with a true to let user in */
return this.auth
.asObservable()
.filter(auth => {
return auth ? true : false;
})
.map(x => {
console.log("TEST 1000");
return true;
});
}
当我运行应用程序时,即使我看到控制台输出指示返回路径未激活。
我想知道我的逻辑中是否有错误的想法,或者是否有聪明的想法来调试这个问题。
最佳答案
我正在使用此项检查身份验证以及用户是否为管理员:
身份验证服务:
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { AngularFire } from 'angularfire2';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Rx';
@Injectable()
export class AuthService {
admin$: Subject<boolean>;
private user: any = null;
constructor(private af: AngularFire, private router: Router) {
this.admin$ = <Subject<boolean>>new Subject();
this.af.auth.subscribe(
auth => {
if(auth){
this.user = af.database.object(`users_list/${auth.uid}`).subscribe(
res => {
this.user = res;
this.admin$.next(this.user.role === 10);
this.admin$.complete();
},
err => this.admin$.error(err)
);
}else{
this.router.navigate(['auth']);
this.admin$.next(false);
this.admin$.complete();
}
}
);
}
doLogin(credentials){
this.admin$ = <Subject<boolean>>new Subject();
this.af.auth.login(credentials);
}
admin() {
return this.admin$;
}
}
身份验证保护服务:
constructor(private authService: AuthService, private router: Router) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
this.authService.admin().subscribe(
res => {
// Navigate to the login page
if(!res) {
this.router.navigate(['/auth']);
}
},
err => console.log(err),
() => {
// console.log('auth guard can activate complete')
}
);
return this.authService.admin();
}
现在,这与您的问题有什么关系,如果不在
complete()
上调用admin$
,它将不起作用。控制台将记录true
,但路由器不会导航到下一个状态。我基本上还在掌握可观察性的诀窍(因此实现性很差),如果你能修改你的代码,我真的很想看到最终的结果,因为它看起来更干净,而且可能是更好的方法。干杯!