1
votes

I created Angular 5 project and create one factory which should provide metadata from service before application start. The problem is that I get error:

RangeError: Maximum call stack size exceeded
    at resolveNgModuleDep (core.js:10559)
    at _callFactory (core.js:10649)
    at _createProviderInstance$1 (core.js:10599)
    at resolveNgModuleDep (core.js:10581)
    at _createClass (core.js:10622)
    at _createProviderInstance$1 (core.js:10596)
    at resolveNgModuleDep (core.js:10581)
    at NgModuleRef_.get (core.js:11806)
    at new MetadataService (metadata.service.ts:23)
    at _createClass (core.js:10622)

App module:

@NgModule({
  declarations: [
      AppComponent,
      ...
  ],
  imports: [
      BrowserModule,
      HttpClientModule,
      AppRoutingModule,
      FormsModule,
      FlexLayoutModule,
      I18NextModule.forRoot()
  ],
  providers: [
      { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true },
      MetadataService,
      { provide: APP_INITIALIZER, useFactory: MetadataProviderFactory, deps: [MetadataService], multi: true },
      { provide: APP_INITIALIZER, useFactory: I18NextProviderFactory, deps: [I18NEXT_SERVICE], multi: true }      
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Metadata service:

import { Injectable, Injector } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';   

@Injectable()
export class MetadataService {   
    private http: HttpClient;

    constructor(private injector: Injector) { 
        this.http = injector.get(HttpClient);  // this row makes a problem
    }

This row makes a problem.

 this.http = injector.get(HttpClient);

I put this line avoid circular reference and I get "Maximum call stack size exceeded". Where I am wrong ?

1
Why don't inject the HttpClient in the constructor ? - ADreNaLiNe-DJ
Because I get 'Cannot instantiate cyclic dependency!' error. - Milos
@Milos any updates? I am running into something similar, I was able to fix it by delaying the http call using a setTimeout. (I had a call made the instant the service was created) - Ka Mok
@Ka Mok I solved my problem with your suggestion. Actually I postponed injector.get(HttpClient) to my method instead of constructor. It is similar as you did with timeout, probably is not possible to do it in constructor. You can add your comment as an answer :). - Milos

1 Answers

3
votes

You can temporarily get over this by delaying your http call that you make on service init, with a simple setTimeOut (don't need any seconds). I've gone through a few open Angular threads and the main issue has to do with HttpInterceptor and circular depedenecy with the HttpClient.