2017-11-15 5 views
1

所有者だけがアクセスできるユーザー設定ページがあります。 CanActivateを使用して制限を実装したいと考えています。 CanActivateは、出力をブール値またはブール値のオブザーバブルにする必要があります。しかし、私のコードは、ブール値の観測値の観測値を出力します。ここでCanActivate:Observable ObservableをObservableに変換します。<boolean>をObservableに変更します。<boolean>

Type 'Observable<Observable<boolean>>' is not assignable to type 'boolean | Observable<boolean> | Promise<boolean>'. 

私のコードに観察を平らにするために

@Injectable() 
export class UserGuard implements CanActivate { 

    constructor(
    private route: ActivatedRoute, 
    private userService: UserService 
) { } 

    canActivate() { 
    const username = this.route.snapshot.paramMap.get('username'); 

    return this.userService.authState().map(auth => { 
     return this.userService.getByUid(auth.uid).map(user => { 
     return user.username === username ? true : false; 
     }); 
    }); 
    } 
} 

答えて

0

使用.switchMap。以上、ここでそれについて読む:https://www.learnrxjs.io/operators/transformation/switchmap.html

をあなたは、観察が加入され、その値が放出され、それ自体の観察可能ではなく、放出さことを、返され、観察や観測可能なインナーソースに.switchMapをチェーン本来ならば:

return this.userService.authState().switchMap(auth => { 

この場合、元の観測可能なストリームに.mapを連鎖することによって、コードをわずかに平坦化することもできます。

return this.userService.authState().switchMap(auth => 
    this.userService.getByUid(auth.uid) 
).map(user => user.username === username); 
関連する問題