Angular 2动态更改默认路由

Sa *_*gin 11 javascript angular2-routing angular

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

例如,当他们登录时,他们会重定向到Day,但是他们希望能够更改它并在他们登录时的周或月重定向.

  { path: 'planification', component: PlanificationComponent,
   children: [
   { path: '', redirectTo: 'Day', pathMatch: 'full' },
   { path: 'day', component: DayComponent },
   { path: 'week', component: WeekComponent },
   { path: 'month', component: MonthComponent }]
 }
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

@ angular/core:2.4.7

@ angular/router:3.4.7

谢谢你的帮助!

Vad*_*imB 11

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

{ path: '', canActivate: [UserSettingsGuard], redirectTo: 'Day', pathMatch: 'full' }
Run Code Online (Sandbox Code Playgroud)

你看起来像这样:

@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;
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

因此,当具有覆盖页面的用户存在时,您可以切换到新URL,或者使用默认流程.

  • 如果您添加“children: []”,它应该可以工作,并且您不必指定组件。 (3认同)