나는 angular2active 호를 처리하는 경우에는 사용자가 로그인하지 않은,그것을 리디렉션하여 로그인 페이지:
import { Injectable } from "@angular/core";
import { CanActivate , ActivatedRouteSnapshot, RouterStateSnapshot, Router} from "@angular/router";
import {Observable} from "rxjs";
import {TokenService} from "./token.service";
@Injectable()
export class AuthenticationGuard implements CanActivate {
constructor (
private router : Router,
private token : TokenService
) { }
/**
* Check if the user is logged in before calling http
*
* @param route
* @param state
* @returns {boolean}
*/
canActivate (
route : ActivatedRouteSnapshot,
state : RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
if(this.token.isLoggedIn()){
return true;
}
this.router.navigate(['/login'],{ queryParams: { returnUrl: state.url }});
return;
}
}
나는 그것을 구현하기 위해 각 경로에 다음과 같:
const routes: Routes = [
{ path : '', component: UsersListComponent, canActivate:[AuthenticationGuard] },
{ path : 'add', component : AddComponent, canActivate:[AuthenticationGuard]},
{ path : ':id', component: UserShowComponent },
{ path : 'delete/:id', component : DeleteComponent, canActivate:[AuthenticationGuard] },
{ path : 'ban/:id', component : BanComponent, canActivate:[AuthenticationGuard] },
{ path : 'edit/:id', component : EditComponent, canActivate:[AuthenticationGuard] }
];
더 좋은 방법이 있을 구현하 canActive 옵션을 추가하지 않고 각각의 경로입니다.
내가 무엇을 원하는 추가에 주요 경로는,그리고 적용해야 하는 모든 다른 노선이 있습니다. 나는 검색을 많지만,나를 찾을 수 없습 유용한 솔루션
감사
할 수 있습을 소개하 componentless 부모로서 적용 가드가 있:
const routes: Routes = [
{path: '', canActivate:[AuthenticationGuard], children: [
{ path : '', component: UsersListComponent },
{ path : 'add', component : AddComponent},
{ path : ':id', component: UserShowComponent },
{ path : 'delete/:id', component : DeleteComponent },
{ path : 'ban/:id', component : BanComponent },
{ path : 'edit/:id', component : EditComponent }
]}
];
할 수도 있습니다 subscribe 라우터's 로를 변경합니다.component's ngOnInit 기능과 체크 인증을 거기서에서 예:
this.router.events.subscribe(event => {
if (event instanceof NavigationStart && !this.token.isLoggedIn()) {
this.router.navigate(['/login'],{ queryParams: { returnUrl: state.url}});
}
});
이러한 방식의 응용 프로그램의 모든 종류의 넓은 체크인(s)을 때 경로를 변경합니다.
이 예제를 검색할 때었으로 예시에서 주어진 예입니다.
는지 확인해야 합 guard 경우 true 를 반환합니다 당신을 보여주고 싶은 아이 노선이 있습니다.
@Injectable()
export class AuthenticationGuard implements CanActivate {
constructor(
private router: Router,
private authService: AuthService) { }
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
): Observable<boolean> | Promise<boolean> | boolean {
// Auth checking code here
// Make sure you return true here if you want to show child routes
return true;
}
}