我的身份验证服务几乎可以正常工作,但问题是如果用户登录或未从异步 http 请求中登录,我正在获取信息。
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 ActivationGuard implements CanActivate {
constructor(private router: Router, private userService: UserAuthenticationService) {
}
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.userService.isUserAuthenticated == false) {
this.router.navigate(['/']);
return false;
}
return true;
}
}
UserAuthenticationService.ts
import {Injectable, OnInit} from '@angular/core';
import {Http} from '@angular/http';
@Injectable()
export class UserAuthenticationService implements OnInit {
isUserAuthenticated: boolean = false;
username: string = 'admin';
constructor(private http: Http) {}
ngOnInit(){
this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
.subscribe(res => {
this.isUserAuthenticated = res.json();
},
err => {
console.error('An error occured.' + err);
});
}
}
每次我得到false
(即使我已登录,它也不允许我进入应用程序)。
但是,如果我将文件中的isUserAuthenticated: boolean = false;
行更改为- 它永远不会把我踢出去 -总是正确的。UserAuthenticationService.ts
true
isUserAuthenticated
可能是由http请求引起的并且它是异步的吗?或者也许有更好的方法来处理它?
期待任何帮助。谢谢你。