我想這是一個非常簡單的問題,但不幸的是我不知道如何處理它。將驗證服務與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