angular - 拒绝访问 Angular js 2 中的路由

标签 angular

我有一个包含路由的文件,想在用户未完成登录时拒绝访问某些路由,我该怎么做?

我的路线

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/

相关文章:

html - 如何调整垫子选择高度以适合其元素?

javascript - 将模板添加为 innerHTML 时 Angular 2 绑定(bind)/事件不起作用

angular - Angular 6 中未找到任何配置或已弃用 get/set

javascript - Ionic v2 中的布局页面

Angular2 - 如何将字符串枚举与 *ngIf 一起使用

javascript - 类型 '{ period: any; prices: any; }' 的参数不可分配给类型 'MAInput' 的参数

Angular 4 : Bootstrap's collapse does not work using data-target attribute

javascript - 根据权限名称过滤用户

javascript - Angular 中的入口组件需要选择器吗?

javascript - Dx数据网格 : Validating multiple edit fields at once