无法阅读财产' get'未定义的角度4

时间:2018-06-02 17:31:59

标签: angular

我正在尝试在我的配置服务中注入HttpClient,如:

import { Http } from '@angular/http';
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';


export function config() {
   return new Configuration();
}


@Injectable()
export class Configuration {

    public static createConfiguration(): any {
        return config;
    };

    constructor(private http?: HttpClient) {
        debugger;
        if (environment.production) {            
            this.readConfigurations().subscribe(res => {
                console.log(res);
            })

        }
    }



    readConfigurations() {
        return this.http.get('../../assets/config/config.json')
            .map((res: any) => {
                res.json();
            }
            );
    }
}

所以,你可以看到我在构造函数参数中注入了HttpClient

在我的app模块中,我已在

下声明了此配置

提供商:

   { provide: Configuration, useFactory: Configuration.createConfiguration(), deps: [] },

但是,当我运行我的应用程序时,我得到了:

  

ERROR TypeError:无法读取属性' get'未定义的           在Configuration.webpackJsonp ... / .. / .. / .. / .. / src / app / config / configuration.service.ts.Configuration.readConfigurations   (configuration.service.ts:69)           在新的配置(configuration.service.ts:59)           在config(configuration.service.ts:10)           at _callFactory(core.es5.js:9552)           at _createProviderInstance $ 1(core.es5.js:9506)           at resolveNgModuleDep(core.es5.js:9488)           at _createClass(core.es5.js:9533)           at _createProviderInstance $ 1(core.es5.js:9503)           at resolveNgModuleDep(core.es5.js:9488)

请帮我解决我的错误。

编辑:

应用模块:

@NgModule({
  imports: [HttpClientModule],
  declarations: [
    AppComponent,

    ],
  providers: [
    Logger, LOG_LOGGER_PROVIDERS,
    { provide: Configuration, useFactory: Configuration.createConfiguration(), deps: [] },
   ],
  bootstrap: [AppComponent]
})

1 个答案:

答案 0 :(得分:0)

让它发挥作用:

@NgModule中,您需要为HttpClient部分提供deps的依赖关系。

变化:

{ provide: Configuration, useFactory: Configuration.createConfiguration(), deps: [] },

为:

{ provide: Configuration, useFactory: Configuration.createConfiguration(), deps: [HttpClient] },

并在您的Configuration对象中,您需要将HttpClient作为依赖注入添加到导出的config函数顶部并将其传递给构造函数:

变化:

export function config() {
  return new Configuration();
}

为:

export function config(http: HttpClient) {
   return new Configuration(http);
}

否则,角度框架工厂机制不知道它需要将HttpClient传递给您的对象。这应该有效(对我而言)

话虽这么说,从构造函数访问网络仍然是非常糟糕的做法。