[英]Angular2 routing canActivate and AuthGuard (JWT) with user role parameter
[英]Angular2: canActivate
当前,我想实现canActivate函数,我想要的一切都是每次请求页面时向服务器发送一个请求,并在json响应中获取true / false,以便了解用户身份验证并允许其查看当前页面。 看来我完全迷住了可观察和承诺对象,这对我来说是新的,到目前为止我有什么。
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();
}
}
一些变化
@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
,而是会得到一个Observable
,它最终会发出true
或false
值
我们要做的是返回从isAuthenticated()
获得的可观察值
在isAuthenticated with return the observable we get from
this.http.get() isAuthenticated with return the observable we get from
对象, and transform the emitted event. It seems the response from the server (
and transform the emitted event. It seems the response from the server (
) is not used. Therefore we use
and transform the emitted event. It seems the response from the server (
res.json() ) is not used. Therefore we use
and transform the emitted event. It seems the response from the server (
) is not used. Therefore we use
) is not used. Therefore we use
in case of an error and
) is not used. Therefore we use
catch() to return
false in case of an error and
否则to return
true。
因为未使用来自服务器的响应,所以可以省略.map((res : Response) => res.json())
,除非您希望从该false
返回false
情况。 此外,您的生产代码可能看起来有所不同,并且需要处理响应。
我们不会在任何地方订阅,因为这是路由器从canActivate
返回Observable
时所做的事情,并且如果我们调用canActivate
subscribe()
,则会得到Subscription
而不是Observable
。
canActivate
可以返回Observable<boolean>
, Promise<boolean>
或boolean
。
由于您依赖异步检查,因此无法返回布尔值。
但是,看起来您可以轻松完成
canActivate(): Observable<boolean> {
return this.isAuthenticated();
}
我还不是Observable
专家,但是如果您未经授权,也可以很容易地链接到重定向呼叫。
这是适合我的解决方案:
canActivate() {
return this.http.get("/index.php?module=Api&action=IsAuthenticated")
.toPromise()
.then(this.extractData)
.catch(this.handleError);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.