Can't get Observable.of(true) to work in an AuthGuard in Angular2

风格不统一 提交于 2019-12-24 11:18:13

问题


Using Angular with AngularFire2 (Firebase package) and am trying to use a guard to prevent all users except one from accessing a specific route. But the code below won't work. I get the error:

Class 'AuthGuard' incorrectly implements interface 'CanActivate'. Type 'void' is not assignable to type 'boolean | Observable | Promise'.

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';
import { AngularFire, FirebaseListObservable } from 'angularfire2';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(private af: AngularFire) { }

  canActivate() {
    this.af.auth.subscribe(auth => {
      if (auth.uid === 'xyz123') {
        return Observable.of(true);
      } else {
        return Observable.of(false);
      }
    })
  }
}

回答1:


  canActivate() {
    return this.af.auth
    .map(auth => {
      return auth.uid === 'xyz123';
    })
  }

The router expects a boolean or Observable<boolean> but if you call subscribe canActivate will return a Subscription. If you use map the return value will be an Observable.



来源:https://stackoverflow.com/questions/42317622/cant-get-observable-oftrue-to-work-in-an-authguard-in-angular2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!