route navigation is not working in angular 9

Viewed 8499

I am working on a login and home component in my angular app.

Login service is validating the username and password of the user.

After successful login, it should redirect user to the home page.

But router redirect is not working properly.

login component

import { Router } from '@angular/router';
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

import { User } from 'src/app/shared/models/user';

import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {

  userName: FormControl;
  password: FormControl;
  loginFormGroup: FormGroup;
  loginError: boolean;
  errorMessage: string;
  messageString: string;

  constructor(private router: Router, private authService: AuthService) { }

  ngOnInit() {
    this.userName = new FormControl("", [Validators.required]);
    this.password = new FormControl("", [Validators.required]);
    this.loginFormGroup = new FormGroup({
      userName: this.userName,
      password: this.password
    });
  }

  login() {
    this.loginError = false;
    if (this.loginFormGroup.valid) {
      let user: User = new User();
      user.userId = this.userName.value;
      user.password = this.password.value;
      this.authService.login(user)
        .subscribe(res => 
        {
          console.log(res)
          this.router.navigate(["home"])
          console.log("res")
        },
        error =>
        {
          console.log(error)
        });
    }
  }
}

and login service

import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
import { Observable } from "rxjs";
import { share } from "rxjs/operators";
import { environment} from 'src/environments/environment';
import { HttpClient, HttpParams, HttpHeaders} from "@angular/common/http";
import { User } from 'src/app/shared/models/user';

@Injectable({ providedIn: "root" })
export class AuthService {
  user: User;
  resp=401;

  get userDetail(): User {
    return this.user;
  }

  constructor(
    private router: Router,
    private http: HttpClient
  ) {
  }


  login(user: User): Observable<any> {

    var formData = new FormData();
    formData.append("userId", user.userId);
    formData.append("password", user.password);

    return this.http.get<any>(url+"Validate_Login_User",{
      headers: new HttpHeaders(),
      params: new HttpParams().set("User_Id","user.userId")
    })

  }

}

routes

import { NgModule } from "@angular/core";
import { Routes, RouterModule } from "@angular/router";

import { AuthGuard } from "./authentication/services/auth.guard";

import { LoginComponent } from "./authentication/login/login.component";
import { LayoutComponent } from "./shared/components/layout/layout.component";
import { PageNotFoundComponent } from "./shared/components/page.not.found.component";
import { MenuComponent } from './menu/menu.component';

const routes: Routes = [
  { path: "login", component: LoginComponent },
  {
    path: "home",
    component: HomeComponent,
    canActivate: [AuthGuard],
    children: [
      {
        //childroutes
      },
      {
        //childroutes
      },
    ],
  },
  { path: "**", component: PageNotFoundComponent },
  { path: "Menu", component: MenuComponent}
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      onSameUrlNavigation: "ignore",
      useHash: true,
    }),
  ],
  exports: [RouterModule],
})
export class AppRoutingModule {}

console log in login component

enter image description here

even though the console is printing success, route navigate is not happening and its still in login page

2 Answers

Try this.

 this.router.navigateByUrl('/home');

replace your code with the following piece of code, that should work.

 this.loginError = false;
    if (this.loginFormGroup.valid) {
      let user: User = new User();
      user.userId = this.userName.value;
      user.password = this.password.value;
      this.authService.login(user)
        .subscribe(res => 
        {
          console.log(res)
          this.router.navigate(["/home"])
          console.log("res")
        },
        error =>
        {
          console.log(error)
        });
    }
  }

Edited:

Please replace your ngModule with the below code:

@NgModule({
  imports: [
    RouterModule.forRoot(routes, {
      useHash: true,
    }),
  ],
  exports: [RouterModule],
})
Related