【问题标题】:Angular 2 dynamically change default routeAngular 2 动态更改默认路由
【发布时间】:2017-02-17 14:17:11
【问题描述】:

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

例如,目前,他们在登录时会被重定向到 Day,但他们希望能够更改它并在他们登录时在一周或一个月内重定向。

  { 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/路由器:3.4.7

感谢您的帮助!

【问题讨论】:

    标签: javascript angular angular2-routing


    【解决方案1】:

    实际上,您可以为此使用警卫在导航发生之前重定向到正确的 url:

    { 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 或使用默认流程。

    【讨论】:

    • 无法让此解决方案与 Angular 2.4 一起使用。我必须指定路径和组件。
    • 如果您添加children: [],它应该可以工作,并且您不必指定组件。
    • 我有一种情况,用户将被允许路由到一组路由(将在视图中显示为选项卡),默认情况下应该路由到其中的第一个。如何做到这一点?
    • 除了,该错误导致 canActivate 不会在 Angular 4 中的 redirectTo 路由上被调用...请参阅 https://github.com/angular/angular/issues/18605
    • 这真是……太棒了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 2012-03-17
    • 1970-01-01
    • 2020-01-15
    • 2017-05-28
    相关资源
    最近更新 更多