Angular 6-无法解析APP_INITIALIZER

时间:2018-09-04 07:17:14

标签: angular dependency-injection

我正在尝试在APP_INITIALIZER上加载我的设置,但是编译器抛出错误,无法解析AppSettingService的所有参数。还尝试注入appSettingService构造函数,但编译器仍然抛出相同的错误。

AppSettingService.service.ts

import { AppSettings } from '../_models/appSettings';
import { BaseDataService } from '../base-data.service';
import { HttpClient } from '@angular/common/http';

export class AppSettingsService extends BaseDataService {


appSettings: AppSettings;

constructor(private http: HttpClient) {
    super();
    this.appSettings = null;
    this.setDebugSettings();
}

setDebugSettings() {

    this.appSettings = new AppSettings({
        baseApiUrl: 'http://localhost:3000'
    });
}

load(): Promise<any> {
    return this.http
            .get('http://localhost:3000')
            .map((res: Response) =>  res.json())
            .toPromise()
            .then((data: any) => this.appSettings.baseApiUrl = 'http://localhost:3000')
            .catch( (err) => Promise.resolve());

  }
}

app.module.ts

// factory method to get our config loaded at startup
export function configLoader(appSettingsService: AppSettingsService) {
  return () => appSettingsService.load();
 }
 providers: [
...,
AppSettingsService,
{
  provide: APP_INITIALIZER,
  useFactory: configLoader,
  deps: [AppSettingsService],
  multi: true
},
...

3 个答案:

答案 0 :(得分:0)

AppSettingsService的依存关系为HttpClient,因此您应将其标记为依存关系。试试:

AppSettingsService,
{
  provide: APP_INITIALIZER,
  useFactory: configLoader,
  deps: [AppSettingsService, HttpClient],
  multi: true
},

还要确保导入了HttpClientModule,就像苏伦指出的那样。

答案 1 :(得分:0)

@ANMOL,

尝试一下-可以确保在需要时而不是在toPromise()时兑现了诺言-这发生在我身上,起初并不明显:

 load(): Promise<any> {                                    
    const promise = new Promise((resolve, reject) => {                                    
        this.http
            .get('http://localhost:3000')
            .map((res: Response) =>  res.json())
            .subscribe((data: any) => {
                this.appSettings.baseApiUrl = 'http://localhost:3000';
                resolve();
                return data;
        },
        (err) => {
            console.log(err);
            reject();
        })             
    });

    return promise;
}

答案 2 :(得分:0)

将其放入AppSettingsService的构造函数中

someFunc