目前,我希望实现canActivate函数,我想要的是在每次请求页面时向服务器发送一个请求,并在json响应中得到真/假,以便理解用户身份验证并允许查看当前页面。而且我似乎完全停留在可观察和承诺的对象上,这对我来说是新的,到目前为止我所拥有的是什么。
import { Injectable } from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import { Http, Response } from '@angular/http';
import {Observable, Observer, Subject} from "rxjs/Rx";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private http: Http) {}
canActivate() {
if (this.isAuthenticated()) {
return true;
} {
this.router.navigate(['404']);
return false;
}
}
isAuthenticated() : Observable<boolean> {
var subject = new Subject<boolean>();
this.http.get("/index.php?module=Api&action=IsAuthenticated")
.map((res : Response) => res.json())
.subscribe(res => {
console.log("next: returning true");
subject.next(true);
}, (res) => {
console.log("next: returning false");
subject.next(false);
});
return subject.asObservable().first();
}
}发布于 2016-11-25 13:11:41
以下是对我有效的解决方案:
canActivate() {
return this.http.get("/index.php?module=Api&action=IsAuthenticated")
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}发布于 2016-11-25 10:31:25
几个变化
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router, private http: Http) {}
canActivate() {
return this.isAuthenticated().first(); // not sure if `.first() is still necessary
}
isAuthenticated() : Observable<boolean> {
return this.http.get("/index.php?module=Api&action=IsAuthenticated")
.map((res : Response) => res.json())
.catch(err => return Observable.of(false))
.map(res => {
return true
});
}
}如果isAuthenticated()执行了一些异步执行,我们就得不到true或false,我们得到了一个最终会发出true或false值的Observable
我们要做的是返回我们从isAuthenticated()获得的可观察到的
在isAuthenticated with return the observable we get fromthis.http.get()and transform the emitted event. It seems the response from the server (res.json()) is not used. Therefore we usecatch()to returnfalsein case of an error andtrue`中,否则。
由于没有使用来自服务器的响应,所以可以省略.map((res : Response) => res.json()),但如果返回false,则可能会出现错误。而且,您的生产代码看起来可能不一样,需要处理响应。
我们在任何地方都不订阅,因为当Observable从canActivate返回时,路由器就是这样做的,如果我们调用subscribe(),就会得到Subscription而不是Observable。
发布于 2016-11-25 10:33:15
canActivate可以返回Observable<boolean>、Promise<boolean>或boolean。
由于您依赖于异步检查,所以不能返回布尔值。
然而,看起来你可以简单地做
canActivate(): Observable<boolean> {
return this.isAuthenticated();
}我还不是Observable方面的专家,但是如果你没有授权的话,你也很容易接到重定向的电话。
https://stackoverflow.com/questions/40802734
复制相似问题