掙扎試圖按照可在這裏AuthGuard例如: http://www.sparkbit.pl/angular-2-route-guards-real-life-example/通過AuthGuard在角
不幸的是,在試圖實施ActivationGuard.ts
文件,我收到一些錯誤。
ERROR in C:/Users/app/src/app/ActivationGuard.ts (6,24): Cannot find name 'ActivatedRouteSna
pshot'.)
C:/Users/app/src/app/ActivationGuard.ts (6,55): Cannot find name 'RouterStateSnapshot'.)
C:/Users/app/src/app/ActivationGuard.ts (13,62): Cannot find name 'CurrentUserService'.)
C:/Users/app/src/app/ActivationGuard.ts (15,31): Cannot find name 'ActivatedRouteSnapshot'.)
C:/Users/app/src/app/ActivationGuard.ts (15,62): Cannot find name 'RouterStateSnapshot'.)
這基本上意味着,CanActivate
接口和內部構造內的元件並不限定。
routing
文件:
import { WorksheetAccessGuard } from "./ActivationGuard";
const appRoutes: Routes = [
{ path: '', component: LoginComponent },
{ path: 'app', component: AppComponent, canActivate: [WorksheetAccessGuard] },
{ path: '**', redirectTo: '' }
];
我的問題:從哪裏可以得到這些缺失的元素?我的IDE的
提供的圖像:(紅色字是沒有的部分)
編輯
我已經做了定製服務。我不知道,如果它的精細與否:
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 => {
this.isUserAuthenticated = res.json();
},
err => {
console.error('An error occured.' + err);
});
}
}
現在,我收到了AuthGuard
文件裏面的一些錯誤:
**我的主要目標是與每一個部件改變檢查(當用戶在頁面上瀏覽時)如果他記錄或不記錄。如果沒有 - 將他返回到登錄頁面。
EDIT2
我可以只發布所有的邏輯從AuthGuard
文件中的服務?它看起來像:
import {Injectable} from '@angular/core';
import {Router, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {Observable} from 'rxjs/Observable';
import {UserAuthenticationService} from './UserAuthenticationService';
import {Http} from '@angular/http';
interface CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean>|Promise<boolean>|boolean
}
@Injectable()
export class WorksheetAccessGuard implements CanActivate {
private static username: string;
isUserAuthenticated: boolean = false;
constructor(private router: Router, private userService: UserAuthenticationService, private http: Http) {
}
public canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
this.http.get(`http://localhost/api/auth/isLogged/${this.username}`)
.subscribe(res => {
this.isUserAuthenticated = res.json();
},
err => {
console.error('An error occured.' + err);
});
if (!this.isUserAuthenticated) {
this.router.navigate(['/']);
return false;
}
return true;
}
}
我不明白爲什麼我應該把它放在登錄組件中?我已經在登錄組件中實現了一個身份驗證,但是現在我想檢查每個組件更改(用戶在站點上導航)是否已記錄日誌。如果沒有 - 返回到登錄頁面。我已經提供了一些服務,我會在幾分鐘內在我的問題中發佈。 –
基本上,此處的服務僅用於共享您需要檢查的屬性,以瞭解您的用戶是否已登錄(在我的示例中,我使用了'isAuthenticated')。 所以當你的用戶登錄時,'isAuthenticated'被設置爲'true';並且你的警衛檢查該值以返回「true」或「false」以允許導航或不導航。 如果你沒有屬性來檢查服務,你的警衛不能自己檢查任何東西,並且如果你沒有設置你的服務屬性,你的警衛總是會返回false。 –
如果Guard返回'false',用戶將無法瀏覽頁面?他只能留在登錄組件中,是嗎? –