要解决“HttpClientInMemoryWebApiModule从api/heroes返回404错误”错误,您可以按照以下步骤进行操作:
HttpClientInMemoryWebApiModule
模块,并将其添加到您的应用程序的主模块(通常是app.module.ts
)中。import { HttpClientModule } from '@angular/common/http';
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
@NgModule({
imports: [
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService, { dataEncapsulation: false })
],
// ...
})
export class AppModule { }
InMemoryDataService
)正确实现了createDb
方法,并为api/heroes
返回了正确的数据。import { InMemoryDbService } from 'angular-in-memory-web-api';
export class InMemoryDataService implements InMemoryDbService {
createDb() {
const heroes = [
{ id: 1, name: 'Hero 1' },
{ id: 2, name: 'Hero 2' },
{ id: 3, name: 'Hero 3' },
// ...
];
return { heroes };
}
}
HttpClient
进行HTTP请求。确保您将请求URL设置为api/heroes
。import { HttpClient } from '@angular/common/http';
@Injectable()
export class HeroService {
private heroesUrl = 'api/heroes'; // 注意:URL应为`api/heroes`
constructor(private http: HttpClient) { }
getHeroes(): Observable {
return this.http.get(this.heroesUrl);
}
}
通过按照上述步骤检查和调整您的代码,您应该能够解决“HttpClientInMemoryWebApiModule从api/heroes返回404错误”的问题。