Search code examples
angularpromiserxjsngrx

Convert ngrx actions$ (Observable) to Promise


I have a problem with convert Observable to Promise to use in Angular APP_INITIALIZER

part of my app.module.ts:

import {Actions, ofType} from '@ngrx/effects';
import {MyEffects} from './store/my.effects';
import * as MyActions from './store/my.actions';


function loadPermissions(actions$: Actions) {
  return () => actions$.pipe(ofType(MyActions.fetchPermissionsSuccess)).toPromise() // this promise is dead
}

@NgModule({
  declarations: [AppComponent],
  imports: [
    StoreModule.forRoot({}, {}),
    EffectsModule.forRoot([MyEffects]),
  ],
  providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: loadPermissions,
      deps: [Actions],
      multi: true,
    },
  ],
})
export class AppModule {}

Solution

  • As mentioned in my comment, toPromise() doesn't resolve until the source completes.

    So one easy way to make it complete, is to take only the first:

    actions$.pipe(
      ofType(MyActions.fetchPermissionsSuccess),
      take(1)
    ).toPromise();