我想这是一个非常简单的问题,但不幸的是我不知道如何处理它。将验证服务与AuthGuard连接(简单问题)
我正尝试将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的
@罗伊现在好点了吗? – Kaysh
也许这只是我,但你已经注入验证服务到WorksheetAccessGuard。那么? (你是什么意思“_但我怎么能连接服务与guard_”) –
@罗伊有什么缺失。 – Kaysh