【问题标题】:Auth guard not working身份验证保护不起作用
【发布时间】:2017-10-23 20:09:04
【问题描述】:

我正在尝试使 auth guard 工作,但变量 isLoggedIn 始终保持为 false。我尝试添加为核心模块,但它仍然返回false。我尝试了不同的方法,但都没有奏效。

import { Injectable, Component, Input } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/delay';

@Injectable()
export class AuthService {
    private isLoggedIn: boolean = false;

    constructor(private http: Http) {
    }

    public getIsLoggedIn(): boolean {
        console.log("getIsLoggedIn() = " + this.isLoggedIn); // always false
        return this.isLoggedIn;
    }

    login(email: string, password: string) {
        return this.http.post('http://localhost:1337/login', JSON.stringify({ email: email, password: password }))
            .map((response: Response) => {

                // login successful if there's a jwt token in the response
                let user = response.json();
                if (user) {
                    this.isLoggedIn = true;
                    return JSON.stringify(user);
                }
                return JSON.stringify({ user: "not found" });
            });
    }
}
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { AuthService } from './auth.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

@Injectable()
export class AuthGuardService implements CanActivate {
    constructor(private authService: AuthService) {
    }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this.checkLogin();
    }
    checkLogin(): boolean {
        if (this.authService.getIsLoggedIn()) {
            return true;
        }
        return false;
    }
}

【问题讨论】:

  • 我也有同样的问题。最初我认为它与变量的范围有关。但事实并非如此。你找到任何解决方案了吗?请与我们分享。

标签: angular


【解决方案1】:

登录时

localStorage.setItem('isLoggedin', 'true');

在你的保护下

canActivate() {
        if (localStorage.getItem('isLoggedin')) {
            return true;
        }

        this.router.navigate(['/login']);
        return false;
    }


const routes: Routes = [
    {
        path: '',
        loadChildren: './layout/layout.module#LayoutModule', //Rest of routes that requieres to be logged
        canActivate: [AuthGuard]
    },
    { path: 'login', loadChildren: './login/login.module#LoginModule' }

];

【讨论】:

  • 谢谢您的回复,是的,它会起作用,但我真的很想知道为什么它不会更新变量,一定有什么
  • 但是如果你将季节存储在服务中,当你重新加载页面时,你需要重新登录,这真的是你想要的吗?
  • 是的,我确实想要,但我想了解它为什么不更新变量
  • 调试“if (user) {”时的问题是否始终未定义?
  • 我正在这样做。isLoggedIn = true;但在 authguard 但我没有得到更新的值。它正在获取默认值。这是错误的
【解决方案2】:

要解决您的问题,您需要将变量保存在 sessionStorage 中,如下所示:

public getIsLoggedIn(): boolean {
   var isLoggedIn = sessionStorage.getItem('isLoggedIn')
    console.log("getIsLoggedIn() = " + this.isLoggedIn); // always false
    return this.isLoggedIn;
}

并这样设置:

  login(email: string, password: string) {
        return this.http.post('http://localhost:1337/login', JSON.stringify({ email: email, password: password }))
            .map((response: Response) => {

                // login successful if there's a jwt token in the response
                let user = response.json();
                if (user) {
                    //this.isLoggedIn = true;
          sessionStorage.setItem('isLoggedIn')='true';
                    return JSON.stringify(user);
                }
                return JSON.stringify({ user: "not found" });
            });
    }

你应该很高兴!这就是我在产品代码中使用的。

但是,如果您仍想使用您的变量来保存这样的值,您应该看看 Subjects。 This tutorial 解释的很好。

【讨论】:

  • 谢谢您的回复,是的,它会起作用,但我真的很想知道为什么它不会更新变量,一定有什么
  • 如果你还想通过变量来实现,请看下Angular 2/4中的Subjects。 (例如 private isLoggedIn = new Subject();)
猜你喜欢
  • 2015-08-21
  • 2011-07-03
  • 2016-10-29
  • 2013-06-25
  • 2017-03-06
  • 2013-12-28
  • 2012-10-04
相关资源
最近更新 更多