How to redirect from NgOnInit?

﹥>﹥吖頭↗ 提交于 2019-12-12 04:28:12

问题


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;
  }


来源:https://stackoverflow.com/questions/40887688/how-to-redirect-from-ngoninit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!