如何将 Observable<Response> 转换为 Observable<boolean>。这是在路线守卫内。
代码:
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> {
let obs = this.http
.get(environment.apiUrl + '/admin', { withCredentials: true})
.map<Response, boolean>((res: Response) => { return true; });
return obs;
}
不工作。我不明白错误信息:
The 'this' context of type 'Observable<Response>' is not assignable to method's 'this' of type 'Observable<Response>'.
Type 'Response' is not assignable to type 'Response'. Two different types with this name exist, but they are unrelated.
Property 'body' is missing in type 'Response'.
编辑
在浪费了 1 小时试图理解错误消息后,我改用了这个。似乎工作:
canActivate(next: ActivatedRouteSnapshot,state: RouterStateSnapshot): Observable<boolean> {
debugger;
let subject = new Subject<boolean>();
let authenticated = this.http.get(environment.apiUrl + '/admin/access', { withCredentials: true})
authenticated.subscribe((res) => {
if (res.status == 200)
subject.next(true);
else
subject.next(false);
}, () => {
subject.next(false)
}, () => {
subject.complete();
});
return subject;
}