我有一个包含路由的文件,想在用户未完成登录时拒绝访问某些路由,我该怎么做?
我的路线
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)
];
最佳答案
你可以用 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]
添加到每个路由,它会在您每次更改路由时检查您的身份验证逻辑。
(您的身份验证逻辑将根据您的登录身份验证服务/模块而有所不同)
关于angular - 拒绝访问 Angular js 2 中的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39164933/