javascript - 将身份验证服务与 AuthGuard 连接(简单问题)

标签 javascript angular

我想这是一个很简单的问题,但不幸的是我真的不知道如何处理它。

我正在尝试将我的 UserAuthenticationService 服务与 ActivationGuard 连接。

UserAuthenticationService.ts:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class UserAuthenticationService {
    isUserAuthenticated: boolean = false;
    username: string;

    constructor(private http: Http) {
    }

    authentication() {
        this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
            .subscribe(res => { //^^returns true or false, depending if the user is logged or not
                    this.isUserAuthenticated = res.json();
                },   
                err => {
                    console.error('An error occured.' + err);
                });
    }


}

ActivationGuard.ts

import {Injectable} from '@angular/core';
import {Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {UserAuthenticationService} from './UserAuthenticationService';

interface CanActivate {
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean
}

@Injectable()
export class WorksheetAccessGuard implements CanActivate {

    constructor(private router: Router, private userService: UserAuthenticationService) {
    }

    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

        if (this.userService) {
            this.router.navigate(['/']);
            return false;
        }
        return true;
    }
}

注意事项

如果我只使用 localStorage 来存储用户登录与否的信息,效果很好:

public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    if (!localStorage.getItem('currentUser')) {
        this.router.navigate(['/']);
        return false;
    }
    return true;
}

但是如何将服务与守卫连接起来呢?期待任何形式的帮助。提前谢谢你。

如果您需要更多信息,请告诉我,我将编辑我的帖子。

最佳答案

在构造函数中或在 ngOnit 中调用 UserAuthenticationService 的 authentication() 方法,然后它设置 isUserAuthenticated 变量并在 ActivationGuard.ts 中使用它

UserAuthenticationService.ts:

import {Injectable} from '@angular/core';
import {Http} from '@angular/http';

@Injectable()
export class UserAuthenticationService {
    isUserAuthenticated: boolean = false;
    username: string;

    constructor(private http: Http) {
    this.authentication();
    }

    authentication() {
        this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
            .subscribe(res => { //^^returns true or false, depending if the user is logged or not
                    this.isUserAuthenticated = res.json();
                },   
                err => {
                    console.error('An error occured.' + err);
                });
    }


}  

ActivationGuard.ts

 @Injectable()
export class WorksheetAccessGuard implements CanActivate {

    constructor(private router: Router, private userService: UserAuthenticationService) {
    }

    public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

        if (this.userService.isUserAuthenticated) {
            this.router.navigate(['/']);
            return false;
        }
        return true;
    }
}

关于javascript - 将身份验证服务与 AuthGuard 连接(简单问题),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43657760/

相关文章:

Angular 6在回车键上添加输入

javascript - 无法获取 asp :Checkbox ID for jquery in .net c#

javascript - 动态添加的 JavaScript 覆盖 html 页面 View (而不是代码)

javascript - 如何通过窗口 :scroll target using @HostListener to trigger an Observable. fromEvent() 订阅?

node.js - 在客户端和服务器 Mongoose 模型之间共享 typescript 接口(interface)

java - 如何使用 Angular 4 登录?我们使用的主题是使用 fack-bakcend 提供者概念?

php - 删除下拉列表中的重复项

javascript - 您使用哪种 JavaScript BDD 框架?

node.js - 如何通过apache连接 Node 服务器?

Angular2 不加载嵌套组件