Angular 2动态更改默认路由

问题描述 投票:9回答:1

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

例如,现在,当他们登录时,他们会重定向到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 / router:3.4.7

谢谢你的帮助!

javascript angular angular2-routing
1个回答
9
投票

实际上,在导航发生之前,您可以使用警卫重定向到正确的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,或者使用默认流程。

© www.soinside.com 2019 - 2024. All rights reserved.