#APP not getting initialized when useFactory returns empty

1 messages · Page 1 of 1 (latest)

sullen bear
#

I have this factory in a kringenModule which is imported in my app.component


function initializeAppFactory(kringenService: KringenService, environmentService: EnvironmentService): () => Observable<Kring[]> {
  return () => kringenService.setKringen(environmentService.deelnemernummer)
 }

  @NgModule({
    providers: [{
      provide: APP_INITIALIZER,
      useFactory: initializeAppFactory,
      deps: [KringenService, EnvironmentService],
      multi: true
    }]
  })
  export class TkpKringModule {}

As you can see it calls a setKringen() function in a service:


  setKringen(deelnemerNummer: string): Observable<Kring[]> {
    const serviceUrl = `${this.baseUrl}/api/v1.0/collectiviteitkringen/${deelnemerNummer}`

    return this.http.get<Kring[]>(serviceUrl)
      .pipe(
        tap((kringen) => this.kringenSubject$.next(kringen)),
        catchError((error: unknown) => {
          this.logService.error('err,', error);
          // Omdat we aan de gebruiker een foutmelding willen tonen als het laden van opties mislukt.
          return EMPTY;
        })
      );
  }

The problem here is that the http.get can fail in certain situations (a user not having a specific set of data). It can return a 404. If that happens I can see the error logged in the console but the application stops loading.

Is there a way to fix this?

grand terrace
#

My guess is that your app needs this.kringenSubject$.next(kringen) to be called in order to properly load. So, decide what whould be passed to this subsject in case of error.

sullen bear
#

I've changed the return value in the catchError to an empty array but there's no progress.

The kringenSubject$ is defined as a behaviorSubject with an inital value of a empty array: `

private kringenSubject$ = new BehaviorSubject<Kring[]>([]);
kringen$ = this.kringenSubject$.asObservable();

I only use the subject in this method to modify a URL if a user has Kringen

  getUrl(url: string): Observable<string> {
    return this.kringen$
      .pipe(
        map((kringen) => kringen.length > 0 ? `${url}?kring=HC` : url),
        // eslint-disable-next-line rxjs/no-implicit-any-catch
        catchError((err: any) => {
          this.logService.error('err,', err);
          return of(err)
        })
      )
  }

so wether or not kringen$.next() is called shouldn't really mather right? If it's not called the getUrl method should (and does) return the original url.

I think there might an issue with getting a 404 request because if I log in with a different user the app loads as excpected.