如果用户设置了adminflag(在使用angularfire2的Firebase中),我想检查我的adminauthguard
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> | boolean {
return this.loginservice.af.auth.map((auth) => {
if(auth == null) {
return false;
} else {
this.membersservice.get(auth.uid).subscribe(users => {
if(users.admin == true) {
return true;
} else {
return false;
}
})
}
});
如何在可观察的内部解析observable?
答案 0 :(得分:14)
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):Observable<boolean> | boolean {
return new Observable<boolean>( observer => {
this.loginservice.af.auth.map((auth) => {
if(auth == null) {
observer.next(false);
} else {
this.membersservice.get(auth.uid).subscribe(users => {
if(users.admin == true) {
observer.next(true);
} else {
observer.next(false);
}
})
}
});
不是1000%确定这是否适用于您的服务Observables,因为我不完全知道Angular2的Firebase(仅限iOS),但是这样您创建了一个只根据内部发生的事件发出值的observable关闭。
您可能需要确保(通过测试)的唯一方法是您不会遇到未定义的状态,例如类似异步危险的地方,你们都发出真假。
答案 1 :(得分:4)
我需要等待用户Suscription信息才能运行任何安全组件。我使用类似于lastWhisper的解决方案,实现canActivateChild并设置路由:
path: 'app', component: FullLayoutComponent, data: {title: 'Home'}, canActivateChild: [CanActivateChildTeam],
CanActivateChildTeam Service:
import {Injectable, OnDestroy} from "@angular/core";
import {CanActivateChild} from "@angular/router";
import {Meteor} from 'meteor/meteor';
import {Router} from '@angular/router';
import {Observable} from "rxjs/Rx";
import {MeteorObservable} from 'meteor-rxjs';
import {Subscription} from 'rxjs/Subscription';
@Injectable()
export class CanActivateChildTeam implements CanActivateChild, OnDestroy {
allow:Observable<boolean>;
private _userSub:Subscription;
constructor(private router:Router) {
}
canActivateChild(route:any, state:any):Observable<boolean> | Promise<boolean> | boolean {
return this.getUser();
}
getUser() {
if (this.allow) {
this.allow = new Observable(observer => {
observer.next(true);
observer.complete();
});
return this.allow;
}
if (Meteor.userId()) {
this.allow = new Observable(observer => {
if (this._userSub)
this._userSub.unsubscribe();
this._userSub = MeteorObservable.subscribe('user', Meteor.userId()).subscribe(
() => {
observer.next(true);
observer.complete();
}
);
});
return this.allow;
}
else {
this.router.navigate(['/']);
}
}
ngOnDestroy():void {
if (this._userSub)
this._userSub.unsubscribe();
}
}