How to redirect from NgOnInit?

2019-09-14 23:08发布

问题:

I want to redirect, under certain conditions, when the page is loaded or before. For example, Cookies have to have something, then do a redirect.

this.router.navigate(["details"]); in AppComponent.NgOnInit not working!

Routers:

const APP_ROUTES : Route[] = [
  { path: '', component: FormComponent, children: FORM_ROUTES},
  { path: 'details', component: DetailsComponent}
];

Module imports and bootstrap:

imports: [
BrowserModule,
FormsModule,
HttpModule,
RouterModule.forRoot(APP_ROUTES),
RouterModule.forChild(FORM_ROUTES)
],
bootstrap: [AppComponent]

Angular 2.

回答1:

CanActivate decided my problem

In Router

{ path: '', component: FormComponent, children: FORM_ROUTES},
{ path: 'details', component: DetailsComponent, canActivate [NoAuthRedirectService]}

In NoAuthRedirectService

canActivate() : boolean
  {
    if(!this.auth.OnAuth())
    {
      this.router.navigate(["/"]);
      return false;
    }
    return true;
  }