【问题标题】:Convert ngrx actions$ (Observable) to Promise将 ngrx actions$ (Observable) 转换为 Promise
【发布时间】:2021-08-26 20:31:10
【问题描述】:

我在将 Observable 转换为 Promise 以在 Angular APP_INITIALIZER 中使用时遇到问题

我的 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 {}

【问题讨论】:

  • 我也讨厌诺言死了:(
  • 死了是什么意思?我没明白你的意思
  • 现在更严重的是——promise 永远无法解决的问题吗?那是因为 toPromise() 只会在 observable 完成时解决。在运算符ofType之后添加take(1)
  • 上帝保佑你@olivarra1/写这个评论作为答案,我想给你+1 :)

标签: angular promise rxjs ngrx


【解决方案1】:

正如我在评论中提到的,toPromise() 在源代码完成之前不会解析。

所以一个简单的方法来完成它,就是只取第一个:

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

【讨论】:

    猜你喜欢
    • 2017-01-12
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 2018-02-19
    • 2018-08-22
    • 2016-08-15
    相关资源
    最近更新 更多