无法获取Observable.of(true)以在Angular2的AuthGuard中工作 [英] Can't get Observable.of(true) to work in an AuthGuard in Angular2
问题描述
将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';
})
}
路由器期望一个 boolean
或 Observable< boolean>
,但是如果您调用 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屋!