Angular 2 动态更改默认路由 [英] Angular 2 dynamically change default route

查看:48
本文介绍了Angular 2 动态更改默认路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要允许我的应用程序的用户在需要时更改默认路由:我有一个参数页面,他们可以在其中选择登录时要首先显示的页面".

I need to allow the users of my application to change the default route when they want: I have a parameter page where they can select the "page" they want to show first when log on.

例如,就目前而言,他们在登录时会被重定向到 Day,但他们希望能够更改这一点,并且如果他们愿意,可以在他们登录时在周或月重定向.

For example for now, they are redirected to Day when they log on, but they want to be able to change that and to be redirected on week or month when they log on if they want.

  { path: 'planification', component: PlanificationComponent,
   children: [
   { path: '', redirectTo: 'Day', pathMatch: 'full' },
   { path: 'day', component: DayComponent },
   { path: 'week', component: WeekComponent },
   { path: 'month', component: MonthComponent }]
 }

我该怎么做?

@angular/core: 2.4.7

@angular/core: 2.4.7

@angular/router: 3.4.7

@angular/router: 3.4.7

感谢您的帮助!

推荐答案

实际上你可以使用guards来在导航发生之前重定向到正确的url:

Actually you can use guards for this to redirect to correct url before navigation happens:

{ path: '', canActivate: [UserSettingsGuard], redirectTo: 'Day', pathMatch: 'full' }

你的守卫看起来像这样:

And you guard can looks like this:

@Injectable()
export class UserSettingsGuard implements CanActivate  {
  constructor(private router: Router) { }

  canActivate() : boolean {
    var user = ...;

    if(user.defaultPage) {
      this.router.navigate([user.defaultPage]);
    } else {
      return true;
    }
  }
}

因此,当存在覆盖页面的用户时,您可以切换到新的 url 或改用默认流程.

So you can switch to new url when user with overriden page exists or use default flow instead.

这篇关于Angular 2 动态更改默认路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆