【问题标题】:How to redirect from NgOnInit?如何从 NgOnInit 重定向?
【发布时间】:2017-04-14 17:40:17
【问题描述】:

我想在某些情况下在页面加载时或之前重定向。例如,Cookie 必须有一些东西,然后进行重定向。

AppComponent.NgOnInit 中的this.router.navigate(["details"]); 不起作用!

路由器:

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

模块导入和引导:

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

角度 2。

【问题讨论】:

  • 你应该使用Router Guards来做有条件的重定向。
  • “不工作”是什么意思?你的路线看起来如何。上面的代码包含什么组件?
  • @GünterZöchbauer 已更新
  • 你试过this.router.navigate(["/details"]);(和/)吗?
  • 但是在 AppComponent.ClickToRedirect() 函数中这是有效的。

标签: angular angular-ui-router


【解决方案1】:

CanActivate 决定了我的问题

路由器

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

NoAuthRedirectService

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

【讨论】:

    猜你喜欢
    • 2019-11-30
    • 2017-02-14
    • 1970-01-01
    • 2016-10-06
    • 2019-08-11
    • 2020-04-15
    • 1970-01-01
    • 2017-08-09
    • 2012-04-24
    相关资源
    最近更新 更多