简体   繁体   中英

Angular 4 router.navigate

I have created a login function in the login component of my application

Inside 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(['/']);
            }
          });
    }

Routes configuration:

{ 
    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' 
},

In this function on obtaining the data from the authService, I can see the log first_login in the console but the router does not navigate to thje required url.

My guess is going to be that your module isn't properly set up. Check your console for errors, this will reveal why your route isn't navigable. There may be something wrong in your template but without providing the errors in your console, it's hard/impossible to know what's wrong.

Also, I'd set up an auth guard to prevent people from landing on routes that require authentication.

Also, what component are you rendering for the home route, there doesn't seem to be a route for that, and also that and the first log in route are the routes which should have the auth guard applied to them.

Also, it's possible your auth service login function is throwing an exception, add a catch and log the error.

Please update this question with relevant data so I can assist your further.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM