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

查看:298
本文介绍了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 exemple for now, they are redirect to Day when they log on, but they want to be able to change that and to be redirect 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

感谢您的帮助!

推荐答案

实际上您可以使用警卫来重定向在导航发生之前更正网址:

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

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

你看起来像这样:

@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天全站免登陆