【发布时间】: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