我有一个包含路由的文件,并且当用户没有完成登录时想要拒绝访问某些文件,我该怎么做?
我的路线
import { provideRouter, RouterConfig } from '@angular/router';
import {SymfonyComponent} from './symfony.component';
import {Symfony2Component} from './symfony2.component';
import {Symfony3Component} from './symfony3.component';
import {LoginComponent} from './login.component';
const routes: RouterConfig = [
{
path: 'all',
component: SymfonyComponent
},
{
path: 'one',
component: Symfony2Component
},
{
path: 'post',
component: Symfony3Component
},
{
path: 'login',
component: LoginComponent
},
];
export const appRouterProviders = [
provideRouter(routes)
];
答案 0 :(得分:5)
您可以使用Angular2' AuthGuard
执行此操作,请查看此AuthGuard documentation。
以下是app.routes.ts中使用的示例:
import {AuthGuard} from './app/common/guards/auth.guard';
import {HomeComponent} from './app/home/home.component';
export const Routes : RouterConfig = [{
path: 'home',
component: HomeComponent,
canActivate: [AuthGuard]
}]
然后你需要创建一个后卫,它看起来像这样:
import {Injectable} from '@angular/core';
import {CanActivate, Router} from '@angular/router';
import {FooAuth} from 'foo';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private _fooAuth: FooAuth,
private _router: Router
){}
canActivate() : Observable<boolean>{
return this.isAllowedAccess();
}
private isAllowedAccess() {
if(!this._fooAuth.currentSession) {
this._router.navigate(['/login']);
return Observable.of(false);
}
return Observable
.fromPromise(this._fooAuth.validateSession(this._fooAuth.currentSession))
.mapTo(true)
.catch(err => {
this._router.navigate(['/login']);
return Observable.of(false)
});
}
设置防护后,您可以为每条路线添加canActivate: [AuthGuard]
,每次更改路线时都会检查您的身份验证逻辑。
(您的身份验证逻辑将根据您的登录身份验证服务/模块而有所不同)