首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular2: canActivate

Angular2: canActivate
EN

Stack Overflow用户
提问于 2016-11-25 10:26:40
回答 3查看 381关注 0票数 1

目前,我希望实现canActivate函数,我想要的是在每次请求页面时向服务器发送一个请求,并在json响应中得到真/假,以便理解用户身份验证并允许查看当前页面。而且我似乎完全停留在可观察和承诺的对象上,这对我来说是新的,到目前为止我所拥有的是什么。

代码语言:javascript
复制
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();
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2016-11-25 13:11:41

以下是对我有效的解决方案:

代码语言:javascript
复制
canActivate() {
    return this.http.get("/index.php?module=Api&action=IsAuthenticated")
        .toPromise()
        .then(this.extractData)
        .catch(this.handleError);
}
票数 0
EN

Stack Overflow用户

发布于 2016-11-25 10:31:25

几个变化

代码语言:javascript
复制
@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()执行了一些异步执行,我们就得不到truefalse,我们得到了一个最终会发出truefalse值的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,则可能会出现错误。而且,您的生产代码看起来可能不一样,需要处理响应。

我们在任何地方都不订阅,因为当ObservablecanActivate返回时,路由器就是这样做的,如果我们调用subscribe(),就会得到Subscription而不是Observable

票数 2
EN

Stack Overflow用户

发布于 2016-11-25 10:33:15

canActivate可以返回Observable<boolean>Promise<boolean>boolean

由于您依赖于异步检查,所以不能返回布尔值。

然而,看起来你可以简单地做

代码语言:javascript
复制
canActivate(): Observable<boolean> {
  return this.isAuthenticated();
}

我还不是Observable方面的专家,但是如果你没有授权的话,你也很容易接到重定向的电话。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40802734

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档