【问题标题】:Angular 4 router.navigateAngular 4 router.navigate
【发布时间】:2017-08-16 11:59:29
【问题描述】:

我在我的应用程序的登录组件中创建了一个登录功能

在 LoginComponent.ts 中

 onSubmit(loginForm: NgForm): void {
    if(loginForm.valid) {
      this.authService.login(loginForm.value)
          .then(data => {
            if(data.status && data.status == 'first_login') {
              console.log('in first_login');
              this.router.navigate(['/first-login']);
            } else {
              localStorage.setItem('user', JSON.stringify(data));
              this.router.navigate(['/']);
            }
          });
    }

路由配置:

{ 
    path: 'login', 
    component: LoginComponent 
}, 
{ 
    path: 'not-found', 
    loadChildren: './not-found/not-found.module#NotFoundModule' 
}, 
{ 
    path: 'first-login', 
    loadChildren: './first-login/first-login.module#FirstLoginModule'
}, 
{ 
    path: '**', 
    redirectTo: 'not-found' 
},

在从 authService 获取数据的这个函数中,我可以在控制台中看到日志 first_login 但路由器没有导航到所需的 url。

【问题讨论】:

  • 你的路由器是如何定义的?是像export const AppRoutes: any = [ { path: "/first-login", component: FirstLoginComponent } ];一样定义的
  • 我的路由器定义在一个名为 routing.ts { path: 'login', component: LoginComponent }, { path: 'not-found', loadChildren: './not-found/not-found.module#NotFoundModule' }, { path: 'first-login', loadChildren: './first-login/first-login.module#FirstLoginModule'}, { path: '**', redirectTo: 'not-found' },的文件中

标签: angular angular-routing


【解决方案1】:

我的猜测是您的模块设置不正确。检查您的控制台是否有错误,这将揭示您的路线无法导航的原因。您的模板中可能有问题,但如果不在控制台中提供错误,就很难/不可能知道出了什么问题。

另外,我会设置一个身份验证守卫,以防止人们登陆需要身份验证的路线。

另外,你在为 home 路由渲染什么组件,似乎没有路由,而且第一个登录路由是应该应用 auth 保护的路由。

另外,您的身份验证服务登录函数可能会引发异常,添加一个 catch 并记录错误。

请使用相关数据更新此问题,以便我进一步帮助您。

https://angular.io/guide/router#canactivate-requiring-authentication

【讨论】:

    猜你喜欢
    • 2017-11-03
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    • 2017-12-02
    • 1970-01-01
    • 1970-01-01
    • 2018-03-30
    相关资源
    最近更新 更多