路线导航在 angular 9 中不起作用

route navigation is not working in angular 9

我正在我的 angular 应用程序中开发登录和主页组件。

登录服务正在验证用户的用户名和密码。

登录成功后,应该将用户重定向到主页。

但是路由器重定向工作不正常。

登录组件

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

登录服务

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")
    })

  }

}

路线

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

控制台登录登录组件

即使控制台打印成功,路由导航并没有发生,它仍然在登录页面

用以下代码替换您的代码,应该可以。

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

已编辑:

请用以下代码替换您的 ngModule:

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

试试这个。

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