【问题标题】:Angular in memory web api cyclic dependency with httpClientAngular 内存 Web api 循环依赖与 httpClient
【发布时间】: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


【解决方案1】:

我遇到了同样的问题,这就是我能够解决它的方法,不要注入构造函数,而是尝试在方法中这样做。

从您的 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;
  }

}

【讨论】:

    猜你喜欢
    • 2017-12-26
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    相关资源
    最近更新 更多