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

Angular英雄指南教程:InMemoryWebAPI无法返回JSON数据求助

问题:Angular《英雄指南》教程中InMemoryWebAPI解析失败错误

在进行Angular《英雄指南》Tour of Heroes教程时,配置InMemoryWebAPI后,GET请求http://localhost:4200/api/heroes返回以下错误:

HeroService: getHeroes failed: Http failure during parsing for http://localhost:4200/api/heroes

预期应返回英雄数组,但实际出现JSON解析失败,推测InMemoryDataService未正常加载或注册逻辑存在问题。

涉及文件

in-memory-data.service.ts

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

@Injectable({
  providedIn: 'root',
})
export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const heroes : Hero[] = [
      { id: 12, name: 'Dr. Nice' },
      { id: 13, name: 'Bombasto' },
      { id: 14, name: 'Celeritas' },
      { id: 15, name: 'Magneta' },
      { id: 16, name: 'RubberMan' },
      { id: 17, name: 'Dynama' },
      { id: 18, name: 'Dr. IQ' },
      { id: 19, name: 'Magma' },
      { id: 20, name: 'Tornado' }
    ];
    return {heroes};
  }

  // Overrides the genId method to ensure that a hero always has an id.
  // If the heroes array is empty,
  // the method below returns the initial number (11).
  // if the heroes array is not empty, the method below returns the highest
  // hero id + 1.
  genId(heroes: Hero[]): number {
    return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11;
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';

import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';

import { AppRoutingModule } from './app-routing.module';

import { AppComponent } from './app.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroSearchComponent } from './hero-search/hero-search.component';
import { MessagesComponent } from './messages/messages.component';
import {RouterLink} from "@angular/router";

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    HttpClientModule,
    RouterLink,
    // The HttpClientInMemoryWebApiModule module intercepts HTTP requests
    // and returns simulated server responses.
    // Remove it when a real server is ready to receive requests.
    HttpClientInMemoryWebApiModule.forRoot(
      InMemoryDataService, {dataEncapsulation: false}
    )
  ],
  declarations: [
    AppComponent,
    DashboardComponent,
    HeroesComponent,
    HeroDetailComponent,
    MessagesComponent,
    HeroSearchComponent
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }

app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { DashboardComponent } from './dashboard/dashboard.component';
import { HeroesComponent } from './heroes/heroes.component';
import { HeroDetailComponent } from './hero-detail/hero-detail.component';

const routes: Routes = [
  { path: '', redirectTo: '/dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: DashboardComponent },
  { path: 'detail/:id', component: HeroDetailComponent },
  { path: 'heroes', component: HeroesComponent }
];

@NgModule({
  imports: [ RouterModule.forRoot(routes) ],
  exports: [ RouterModule ]
})
export class AppRoutingModule {}

问题原因分析

解析失败的核心原因是InMemoryWebAPI未成功拦截HTTP请求,导致请求实际访问了不存在的/api/heroes路径,返回的是Angular默认的404 HTML页面,而非预期的JSON数据,HttpClient尝试将HTML解析为JSON时触发错误。可能的诱因包括:

  1. 依赖版本不兼容:angular-in-memory-web-api版本与当前Angular版本不匹配,导致拦截逻辑失效。
  2. 模块导入错误:AppModule中导入了多余的RouterLink,干扰模块初始化流程。
  3. Hero接口定义缺失或错误:Hero接口未正确定义id和name属性,导致InMemoryWebAPI无法正确生成数据。

解决方案

1. 移除多余的RouterLink导入

AppRoutingModule已经导出了RouterModule,无需在AppModule的imports数组中单独导入RouterLink,删除该行:

// 从app.module.ts的imports中移除
RouterLink,

2. 确认Hero接口定义

确保hero.ts中的接口定义正确:

export interface Hero {
  id: number;
  name: string;
}

3. 检查并同步依赖版本

运行以下命令查看当前依赖版本:

npm list @angular/common angular-in-memory-web-api

确保angular-in-memory-web-api的主版本与Angular一致(比如Angular 16对应0.16.x,Angular 17对应0.17.x)。若版本不匹配,安装对应版本:

# 示例:Angular 16安装对应版本
npm install angular-in-memory-web-api@0.16.0

4. 重启开发服务器

修改配置后,重启ng serve,确保所有模块重新加载生效。

验证

完成上述步骤后,直接访问http://localhost:4200/api/heroes,应返回英雄数组的JSON数据,说明InMemoryWebAPI已正常工作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 02:49:54