Auth警卫不工作

时间:2017-10-23 20:09:04

标签: angular

我正在努力使auth警卫工作,但变量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;
    }
}

2 个答案:

答案 0 :(得分: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' }

];

答案 1 :(得分:1)

要解决您的问题,您需要将变量保存在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" });
            });
    }
你应该好好去!这就是我在我的产品代码中使用的内容。

但是,如果您仍想使用变量来保存这样的值,则应该查看“主题”。 This tutorial很好地解释了。