0

I am trying to assign some value (which I got from http request) from another service to provider token in app.module.ts.

My service looks like this:

@Injectable()
export class AppConfigService {
      private appConfig: AppConfig;

      constructor(private http: HttpClient) {}

      loadConfigurationData = () => {
        this.http.get('assets/config/config.json').subscribe(
          (response: AppConfig) => {
            this.appConfig = response;
          },
          error => {
            this.appConfig = {
              baseHref: '/'
            };
          }
        );
};

      getBaseHref(): string {
        return this.appConfig.baseHref;
      }
}

In my app.module.ts I am trying to get this value `baseHref` like that:

@NgModule({  
providers: [
        ...
        AppConfigService,
        {
          provide: APP_INITIALIZER,
          useFactory: (appConfigService: AppConfigService) => () => {
            appConfigService.loadConfigurationData();
          },
          deps: [AppConfigService],
          multi: true
        },
        {
          provide: APP_BASE_HREF,
          useFactory: getBaseHref,
          deps: [AppConfigService],
          multi: true
        },
        ...
      ],
})

export function getBaseHref(appConfigService: AppConfigService): string {
      return appConfigService.getBaseHref();
}

But I got an error: `Cannot read property 'baseHref' of undefined`.

Looks like service is not initialized but why? What's the best way to pass this variable from service to provider?

Aksen P
  • 4,564
  • 3
  • 14
  • 27
johnek smith
  • 53
  • 1
  • 8
  • You should return the `observable` returned from the request to the calling component, where you can either subscribe manually or use the observable directly in the template via the safe navigation operator. – The Head Rush Jun 21 '19 at 13:38

1 Answers1

0

Since you are relying on async data to update your appconfig variable, initially it will be undefined

Appconfig must be initialised :

 private appConfig: AppConfig = {baseref: null} // or default
Jensen
  • 6,615
  • 1
  • 10
  • 12