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

查看:34
本文介绍了无法让 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 但如果你调用 subscribe canActivate 将返回一个订阅.如果您使用 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天全站免登陆