如何将http响应数据从服务传递到app.module.ts

时间:2018-05-15 14:28:42

标签: angular

我制作了一项服务,从后端调用一些api密钥,在app.module.ts全局配置我的应用。该服务称为数据,甚至包括在app init之前,但我不知道如何传入app.module.ts。有人遇到过这种情况吗?

global-settings.service.ts:

@Injectable()
export class GlobalSettingsService {

  apiUrl: any;

  constructor(
    private http: Http,
    @Inject(ORIGIN_URL) private baseUrl: string,
    @Inject(API_PREFIX) private apiPrefix: string
  ) {
    this.apiUrl = this.baseUrl + this.apiPrefix;
   }

  load() {
    return new Promise((resolve, reject) => {
        this.http
            .get(this.apiUrl + 'bootstrap')
            .map(res => res.json())
            .subscribe(response => {
                console.log(response);
                resolve(true);
            });
    });
  }
}

app.module.ts:

export function getUserAuthServiceConfigs() {
  const config = new AuthServiceConfig(
    [
      {
        id: GoogleLoginProvider.PROVIDER_ID,
        provider: new GoogleLoginProvider(// I WANT TO PASS DATA FROM THE SERVICE ABOVE HERE //)
      },
    ]
  );
  return config;
}

export function globalSettingsProviderFactory(provider: GlobalSettingsService) {
  return (data) => provider.load();
}

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule
  ],
  providers: [
    GlobalSettingsService,
    { provide: APP_INITIALIZER, useFactory: globalSettingsProviderFactory, deps: [GlobalSettingsService], multi: true },
    { provide: AuthServiceConfig, useFactory: getUserAuthServiceConfigs },
    { provide: ORIGIN_URL, useValue: '/' },
    { provide: API_PREFIX, useValue: 'api/' }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

这是控制台在app init之前返回的响应:

{
    googleClientId: "abcd"
    reCaptchaKey: "efgh"
}

0 个答案:

没有答案