Angular + .NET Core项目中Http Get请求无法命中Salaries控制器方法
问题:Angular+ASP.NET Core项目中Salaries接口无法命中,页面无数据显示
我使用Visual Studio 2022的Angular+ASP.NET Core模板创建项目,通过「使用Entity Framework的带操作API控制器」选项生成了EmployeesController和SalariesController,对应Employee和Salary模型,前端通过服务类调用后端接口。点击首页的Employees按钮能正常加载员工列表,但点击员工列表里的「View Salary Components」跳转至Salaries页面时,页面无数据,调试发现Salaries控制器的Http Get方法未被命中。
Employees控制器代码
namespace EmployeesAngular.Server.Controllers { [Route("[controller]")] [ApiController] public class EmployeesController : ControllerBase { private readonly EmployeesAngularServerContext _context; public EmployeesController(EmployeesAngularServerContext context) { _context = context; } [HttpGet] public async Task<ActionResult<IEnumerable<Employee>>> GetEmployee() { return await _context.Employee.ToListAsync(); } } }
Salaries控制器代码
namespace EmployeesAngular.Server.Controllers { [Route("[controller]")] [ApiController] public class SalariesController : ControllerBase { private readonly EmployeesAngularServerContext _context; public SalariesController(EmployeesAngularServerContext context) { _context = context; } [HttpGet] public async Task<ActionResult<IEnumerable<Salary>>> GetSalary() { return await _context.Salary.ToListAsync(); } } }
前端相关代码
app.component.html
<div class="container"> <h3 class="d-flex justify-content-center">Employee Details</h3> <nav class="navbar navbar-expand-sm bg-light navbar-dark"> <ul class="navbar-nav"> <li class="nav-item"> <button routerLink="employees" class="m-1 btn btn-light btn-outline-primary" Button>Employees</button> </li> </ul> </nav> <router-outlet></router-outlet> </div>
employees.component.html
<table class="table table-striped"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Department</th> <th>Date Of Joining</th> <th>Total Salary</th> </tr> </thead> <tbody> <tr *ngFor="let dataItem of EmployeeList"> <td>{{dataItem.firstName}}</td> <td>{{dataItem.lastName}}</td> <td>{{dataItem.department}}</td> <td>{{dataItem.joinDate}}</td> <td>{{dataItem.totalSalary}}</td> <td><a routerLink="/salaries" routerLinkActive="active" ariaCurrentWhenActive="page">View Salary Components</a></td> <td><a routerLink="/editEmployee" routerLinkActive="active" ariaCurrentWhenActive="page">Edit</a></td> </tr> </tbody> </table>
salaries.component.html
<table class="table table-striped"> <thead> <tr> <th>Basic</th> <th>Allowance</th> <th>Bonus</th> </tr> </thead> <tbody> <tr *ngFor="let dataItem of SalaryList"> <td>{{dataItem.basic}}</td> <td>{{dataItem.allowance}}</td> <td>{{dataItem.bonus}}</td> </tr> </tbody> </table>
employees.component.ts
import { Component, OnInit } from '@angular/core'; import { ApiserviceService } from '../apiservice.service'; @Component({ selector: 'app-employees', templateUrl: './employees.component.html', styleUrls: ['./employees.component.css'] }) export class EmployeesComponent implements OnInit { constructor(private service: ApiserviceService) { } EmployeeList: any = []; ngOnInit(): void { this.refreshEmpList(); } refreshEmpList() { this.service.getEmployeeList().subscribe(data => { this.EmployeeList = data; }); } }
salaries.component.ts
import { Component, OnInit } from '@angular/core'; import { ApiserviceService } from '../apiservice.service'; import { ActivatedRoute } from '@angular/router'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-salaries', templateUrl: './salaries.component.html', styleUrl: './salaries.component.css' }) export class SalariesComponent implements OnInit { constructor(private service: ApiserviceService) { } SalaryList: any = []; ngOnInit(): void { this.refreshSalary(); } refreshSalary() { this.service.getSalaryList().subscribe(data => { this.SalaryList = data; }); } }
apiservice.service.ts
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiserviceService { constructor(private http: HttpClient) { } getEmployeeList(): Observable<any[]> { return this.http.get<any[]>('employees'); } getSalaryList(): Observable<any[]> { return this.http.get<any[]>('salaries'); } }
app-routing.module.ts路由配置
const routes: Routes = [ { path: 'employees', component: EmployeesComponent }, { path: 'salaries', component: SalariesComponent }, { path: 'editEmployee', component: EditEmployeeComponent }, ];
报错信息
SyntaxError: Unexpected token '<', "<!doctype "... is not valid
已尝试的无效方案
- 修改
getSalaryList方法的responseType为'text',出现编译错误:Type 'Observable' is not assignable to type 'Observable<any[]>'及No overload matches this call - 将
index.html中的<base href="/">改为<base href=".">,无效 - 添加请求头并设置
responseType为'text',仍无法命中控制器方法,且出现NG0900错误
解决方案
1. 修正API请求的相对路径问题
浏览器返回HTML而非JSON,核心原因是请求路径错误:当从/employees页面跳转至/salaries页面后,前端请求salaries的相对路径会变为/employees/salaries,后端无此路由,因此返回Angular的index.html页面,导致JSON解析报错。
修改apiservice.service.ts,给请求路径添加根路径前缀/,确保请求从网站根目录发起:
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable } from 'rxjs'; @Injectable({ providedIn: 'root' }) export class ApiserviceService { constructor(private http: HttpClient) { } getEmployeeList(): Observable<any[]> { return this.http.get<any[]>('/employees'); // 添加根路径前缀 } getSalaryList(): Observable<any[]> { return this.http.get<any[]>('/salaries'); // 添加根路径前缀 } }
2. 验证后端API路由可用性
直接在浏览器地址栏访问https://localhost:xxxx/salaries(替换为你的项目端口),确认是否能返回JSON数据:
- 若无法返回,检查
Salary模型是否在DbContext中正确配置DbSet:public DbSet<Salary> Salary { get; set; } - 确认数据库中
Salary表存在且有数据 - 检查控制器是否被ASP.NET Core自动扫描注册(默认扫描
Controllers文件夹,无需额外配置)
3. 可选:完善Angular路由配置
添加默认路由和404路由,避免路径异常:
const routes: Routes = [ { path: '', redirectTo: 'employees', pathMatch: 'full' }, // 默认跳转至员工列表 { path: 'employees', component: EmployeesComponent }, { path: 'salaries', component: SalariesComponent }, { path: 'editEmployee', component: EditEmployeeComponent }, { path: '**', redirectTo: 'employees' } // 处理未知路径 ];
内容的提问来源于stack exchange,提问作者Daneesha
相关产品推荐
相关产品推荐

