路线导航在角度9中不起作用

时间:2020-07-20 09:56:32

标签: javascript angular angular-ui-router

我正在使用我的角度应用程序处理登录和主页组件。

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

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

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

登录组件

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

控制台登录登录组件

enter image description here

即使控制台打印成功,路由导航仍未发生,并且仍在登录页面中

2 个答案:

答案 0 :(得分:0)

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

 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],
})

答案 1 :(得分:0)

尝试一下。

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