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

Angular 17中in-memory-web-api无法匹配api/heroes路由的问题

问题原因

核心问题是in-memory-web-api未正确拦截HTTP请求,导致api/heroes请求被Angular路由系统当作前端路由路径处理。由于你未定义任何路由,Angular返回了默认的index.html页面,进而引发JSON解析错误;同时路由系统因找不到匹配路径,抛出NG04002错误。

解决步骤

1. 检查InMemoryDataService的实现

确保你创建的InMemoryDataService正确实现createDb()方法,返回包含heroes属性的数据集对象——这是in-memory-web-api模拟接口响应的核心:

import { InMemoryDbService } from 'angular-in-memory-web-api';
import { Hero } from './hero';

export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const heroes = [
      { id: 11, name: 'Dr Nice' },
      { id: 12, name: 'Narco' },
      { id: 13, name: 'Bombasto' }
    ];
    return { heroes }; // 此处key需与请求路径的`heroes`完全对应
  }
}

若该服务未正确返回heroes数据集,in-memory-web-api无法生成预期的JSON响应。

2. 确认依赖包与配置顺序

  • 先确保已安装angular-in-memory-web-api依赖:
    npm install angular-in-memory-web-api
    
  • 在app.config.ts中,HttpClientInMemoryWebApiModule的配置需放在HttpClientModule之后,确保拦截器能正确注册,现有配置结构可保留,但要确认InMemoryDataService的导入路径正确。

3. 调整请求路径格式

将hero.service.ts中的请求路径改为绝对路径开头,避免相对路径解析异常:

private heroesURL = '/api/heroes';

4. 初始化路由数组

即使无需业务路由,也要确保routes数组正确初始化并导入到app.config.ts中:

// 在app.config.ts所在文件顶部添加
import { Routes } from '@angular/router';

const routes: Routes = []; // 空路由数组保证路由系统正常初始化

5. 调试拦截器(可选)

若问题仍存在,可添加调试拦截器确认请求是否被正确拦截:

// 替换app.config.ts中的importProvidersFrom(HttpClientModule)
provideHttpClient(
  withInterceptors([
    (req, next) => {
      console.log('当前请求路径:', req.url);
      return next(req);
    }
  ])
),

若控制台打印/api/heroes但仍返回HTML,说明in-memory-web-api拦截器未生效,需重新检查服务实现与模块配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:23:23