0

Angular 2 路由器 - 注销并且用户尝试导航到登录页面时,我需要 app.ts 重定向。

我正在使用angular 2 的打字稿。

出于某种原因,重定向适用于某些页面。但是当我在构造函数中有代码时,它会命中它。如果未登录,我想立即将用户重定向到主页。

我正在检查他们是否已登录,如果他们未在 app.ts 文件中登录,我将执行此代码:

       this.router.navigate(['Home']);

这适用于基本页面,但是当我尝试访问我的搜索页面时,例如我得到控制台错误,因为它访问组件构造函数。

这是我在 app.ts 文件中的路由配置:

 @RouteConfig([
     { path: '/', component: Home, as: 'Home'},
     { path: '/home', component: Home, as: 'Home' },
     { path: '/login', component: Login, as: 'Login' }, 
     { path: '/register/:id', component: Register, as: 'Register' },
     { path: '/forgotpassword', component: ForgotPassword, as: 'ForgotPassword' },
     { path: '/dashboard', component: Dashboard, as: 'Dashboard' },
     { path: '/search', component: SearchJobs, as: 'Search' },  
     {path:'/**', redirectTo: ['Home']}
 ])
4

3 回答 3

0

如果您使用的是 RC4 版本,请检查CanActivate 接口

您将需要创建一个实现 CanActivate 接口的类并使用canActivate以下属性保护您的路线RouterConfig

查看最新的路由器文档以获取示例。

于 2016-07-20T06:57:53.740 回答
0

您需要按照您的要求将以下代码写入 app.ts。

import {Router,ROUTER_PROVIDERS,RouteConfig, ROUTER_DIRECTIVES,APP_BASE_HREF,LocationStrategy,RouteParams,ROUTER_BINDINGS} from 'angular2/router';

export class AppComponent  {
    constructor(router:Router){
       this.router=router;
       this.router.subscribe((nextValue) => {
       console.log(nextValue)
       if (nextValue !== 'login' && !autheService.isAuthenticated) {
                      this.router.navigate(['/Login']);
       }
}

看看这里 plnkr

如果你考虑 angular1. 我们有,

$scope.$on('$routeChangeStart', function(next, current) { 
   ... you could trigger something here ...
 });

和其他事件,如果路由失败等等使用ui.router处理路由。所以你可以用上面提到的代码替换 Angular1。

我认为你所要求的,可以通过最小的努力来实现。仍然@canActive 其他点是有效的。

我希望这将有所帮助。

于 2016-01-13T06:16:49.380 回答
0

好吧,您已经在此主题上发布了一些内容,但我会在这里回答,以防其他人看到更多。您可以使用 @CanActivate 装饰器重定向用户。这样做是它将在组件初始化之前运行。如果函数返回 true,则组件将加载,否则它将重定向。我想它会去你设定的路线useAsDefault :true;

export CanActivate(options : CanActivateAnnotation) : (hook: (next: ComponentInstruction, prev: ComponentInstruction) =>
                     Promise<boolean>| boolean) => ClassDecorator

@CanActivate((next, prev) => {
      // This must prove to be true for the component @ this route to load
      if(next.urlPath != '/Login'){ 
         return Promise.resolve(this._authService.getIsAuth() 
         && localStorage.getItem('authToken')
      }
      /*
       If CanActivate returns or resolves to false, the navigation is 
       cancelled. If CanActivate throws or rejects, the navigation is also
       cancelled. If CanActivate returns or resolves to true, navigation 
       continues, the component is instantiated, and the OnActivate hook of 
       that component is called if implemented.
      */
   }
);
于 2016-01-13T06:02:09.117 回答