You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular登录页路由异常:访问/login时被自动重定向至根路径

问题分析与解决

核心问题拆解

1. 根路径(http://localhost:4200/)访问重定向

路由配置未定义根路径的匹配规则,同时缺少登录后目标页面main的路由,导致Angular无法正确匹配路由,触发异常重定向。

2. /login页面立即重定向到根路径

大概率是拦截器逻辑错误或TokenStorageService的getUser()方法返回值异常,也可能是路由配置缺失导致的连锁反应。


具体修复步骤

1. 修复路由配置

补充根路径重定向规则、main组件路由及404兜底路由:

// app.routes.ts
import { Routes } from '@angular/router';
import {LoginComponent} from "./auth/login/login.component";
import {RegisterComponent} from "./auth/register/register.component";
// 导入你的Main组件(替换为实际路径)
import {MainComponent} from "./main/main.component";

export const routes: Routes = [
  // 未登录时根路径重定向到登录页
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'login', component: LoginComponent },
  { path: 'register', component: RegisterComponent },
  // 添加登录后跳转的main页面路由
  { path: 'main', component: MainComponent },
  // 404页面重定向到根路径
  { path: '**', redirectTo: '' }
];

2. 修正LoginComponent逻辑

  • 调整表单初始化方式,避免模板加载时loginForm为undefined
  • 确保已登录用户跳转至main页面(而非不存在的路由)
  • 移除登录成功后的冗余页面刷新:
// login.component.ts
import {Component, OnInit} from '@angular/core';
import {FormBuilder, FormGroup, ReactiveFormsModule, Validators} from "@angular/forms";
import {AuthService} from "../../service/auth.service";
import {TokenStorageService} from "../../service/token-storage.service";
import {Router, RouterLink} from "@angular/router";
import {NotificationService} from "../../service/notification.service";
import {MatFormField, MatLabel} from "@angular/material/form-field";
import {MatInput} from "@angular/material/input";
import {MatButton} from "@angular/material/button";

@Component({
  selector: 'app-login',
  standalone: true,
  imports: [
    ReactiveFormsModule,
    MatFormField,
    MatLabel,
    MatInput,
    MatButton,
    RouterLink
  ],
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent implements OnInit{
  public loginForm!: FormGroup;

  constructor(
    private authService: AuthService,
    private tokenStorage: TokenStorageService,
    private notificationService: NotificationService,
    private router: Router,
    private fb: FormBuilder
  ) {
    // 已登录用户直接跳转至main页面
    if(this.tokenStorage.getUser()) {
      this.router.navigate(['/main']);
    }
  }

  ngOnInit(): void {
    this.loginForm = this.createLoginForm();
  }

  createLoginForm(): FormGroup{
    return this.fb.group({
      username: ['', Validators.compose([Validators.required])],
      password: ['', Validators.compose([Validators.required])]
    })
  }

  submit(): void {
    this.authService.login({
      username: this.loginForm.value.username,
      password: this.loginForm.value.password
    }).subscribe(data => {
      console.log(data);

      this.tokenStorage.saveToken(data.token);
      this.tokenStorage.saveUser(data.user);
      this.notificationService.showSnackBar("Successfully logged in");
      // 登录成功跳转至main页面
      this.router.navigate(['/main']);
      // 移除window.location.reload(),避免状态丢失
    }, error => {
      console.log(error);
      this.notificationService.showSnackBar(error.message);
    })
  }
}

3. 修复登录模板的表单绑定错误

  • 为输入框添加matInput指令(Material组件必填)
  • 修正密码框的表单绑定属性:
<div class="login-page">
  <form [formGroup]="loginForm">
    <div class="justify-content-center">
      <mat-form-field appearance="outline">
        <mat-label>Email Address</mat-label>
        <input matInput formControlName="username">
      </mat-form-field>
      <mat-form-field appearance="outline">
        <mat-label>Password</mat-label>
        <input matInput formControlName="password">
      </mat-form-field>
    </div>
    <div id="controls" class="row">
      <button style="width: 20%" [disabled]="loginForm.invalid" (click)="submit()" mat-flat-button color="primary">
        Login
      </button>
      <a routerLink="/register">Register</a>
    </div>
  </form>
</div>

4. 修正拦截器逻辑(若存在)

如果auth-interceptor.service.ts中存在未登录重定向逻辑,需排除login和register页面,避免循环重定向:

// auth-interceptor.service.ts 示例代码
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  const user = this.tokenStorage.getUser();
  const isAuthPage = request.url.includes('login') || request.url.includes('register');

  if (user && user.token) {
    // 为已登录用户的请求添加Token头
    request = request.clone({
      setHeaders: {
        Authorization: `Bearer ${user.token}`
      }
    });
  } else if (!isAuthPage) {
    // 未登录且访问非授权页面时,重定向到登录页
    this.router.navigate(['/login']);
  }

  return next.handle(request);
}

内容的提问来源于stack exchange,提问作者Yehor But

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 16:24:59