【发布时间】:2017-11-06 10:56:26
【问题描述】:
我尝试使用angular-in-memory-web-api(0.5.1 版)。如果我使用本地对象设置“数据库”,这可以正常工作,但如果我尝试通过 http 请求从本地 JSON 文件获取数据并出现以下错误,则会失败:
未捕获的错误:提供程序解析错误: 无法实例化循环依赖! HttpClient("[ERROR ->]"): 在 NgModule AppModule 中./AppModule@-1:-1
只要我将httpClient 包导入我的服务。
app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
// Imports for loading & configuring the in-memory web api
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from 'app/shared/services/in-memory-data.service';
import { AppComponent } from './app.component';
// other imports of app components
@NgModule({
imports: [
BrowserModule,
HttpClientModule,
HttpClientInMemoryWebApiModule.forRoot(InMemoryDataService), // always import after the HttpClientModule
],
declarations: [
AppComponent,
// ...
],
providers: [ // app wide services not concerning the problem ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
in-memory-data.service.ts:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { RequestInfo } from 'angular-in-memory-web-api';
@Injectable()
export class InMemoryDataService implements InMemoryDbService {
// constructor(http: HttpClient) { // this creates the cyclic dependency
constructor() {
}
createDb(reqInfo?: RequestInfo) {
const db = {}
// fetch data from local JSON files and set up "database" object
return db;
}
}
此问题与HttpClientModule 相关还是angular-in-memory-web-api 问题?
【问题讨论】:
-
好吧,如果您要向 json 文件发出请求,请不要使用 InMemoryWebApiModule。为此,只需使用 httpclient 发出 http get 请求。
-
从 JSON 文件初始化内存数据库服务是我想要做的,因此我必须请求 JSON 文件,因为它是相当多的数据...
-
是的,请求 json 文件,而不是 inmemorywebapi。
-
你找到答案了吗?
标签: angular