无法获得Observable.of(true)在Angular2的AuthGuard中工作 [英] Can't get Observable.of(true) to work in an AuthGuard in Angular2

查看:62
本文介绍了无法获得Observable.of(true)在Angular2的AuthGuard中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将Angular与AngularFire2(Firebase软件包)结合使用,并试图使用一种防护措施来阻止除一个用户之外的所有用户访问特定路由.但是下面的代码不起作用.我收到错误消息:

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:

"AuthGuard"类错误地实现了"CanActivate"接口. 不能将类型'void'分配给'boolean |类型.可观察 答应."

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);
      }
    })
  }
}

推荐答案

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

路由器希望使用booleanObservable<boolean>,但是如果调用subscribe,则canActivate将返回Subscription. 如果使用map,则返回值将是Observable.

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.

这篇关于无法获得Observable.of(true)在Angular2的AuthGuard中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆