我尝试使用angular-in-memory-web-api (0.5.1版)。如果我用本地对象设置“数据库”,这很好,但如果我试图通过http请求从本地JSON文件中获取数据,并出现以下错误,它就会失败:
未知错误:提供者解析错误:不能实例化循环依赖!HttpClient ("ERROR ->"):在./ AppModule @-1:-1中的NgModule AppModule中
一旦我将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 { }内存中数据服务:
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问题?
发布于 2017-12-12 11:24:46
我也面临着同样的问题,这就是我如何能够解决它,不要注入构造函数,而是尝试在方法中这样做。
在您的createDB中,您将正确地注入httpclient,而不会出现循环错误。
import { Injectable, Injector } 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 {
httpClient: HttpClient;
constructor(private inject: Injector) {
}
createDb(reqInfo?: RequestInfo) {
const db = {}
this.httpClient = this.inject.get(HttpClient);
// fetch data from local JSON files and set up "database" object
return db;
}
}https://stackoverflow.com/questions/47135302
复制相似问题