代码之家  ›  专栏  ›  技术社区  ›  blgrnboy

RxJS返回带有数组负载的新对象

  •  0
  • blgrnboy  · 技术社区  · 6 年前

    我试图让我的NgRX效果返回一个动作对象。action对象表示“成功”,需要返回所有检索到的机构作为有效负载的一部分。我该怎么做?请注意 mergeMap 不起作用。我需要在检索完所有检索到的机构后将它们作为有效负载的一部分返回。

      @Effect()
      getInstitutions$ = this.actions$
        .ofType(institutionActions.InstitutionActionTypes.GetInstitutions)
        .pipe(
          switchMap(() => {
            const institutions = this.getInstitutions();
            console.log(institutions);
            return this.getInstitutions();
          }),
          mergeMap((institutions: Institution[]) => {
            // return institutions;
            return {
              type: institutionActions.InstitutionActionTypes.GetInstitutionsSuccess,
              payload: institutions
            };
          })
        );
    
    2 回复  |  直到 6 年前
        1
  •  1
  •   timdeschryver    6 年前

    你得动手术 this.getInstitutions() 如所示:

    @Effect()
    getInstitutions$ = this.actions$
      .ofType(institutionActions.InstitutionActionTypes.GetInstitutions)
      .pipe(
        switchMap(() => {
          return this.getInstitutions().pipe(
            map(institutions => ({
              type: institutionActions.InstitutionActionTypes.GetInstitutionsSuccess,
              payload: institutions
            })),
            catchError(_ => ...) //don't forget to handle errors
          )
        })
      );
    

    另外,我鼓励您使用动作创建者,而不是“到处”创建动作对象- Let’s have a chat about Actions and Action Creators within NgRx

        2
  •  0
  •   kashpatel    6 年前

    不如使用“map”instaed mergeMap。你能试着跟着吗?

     @Effect()
      getInstitutions$ = this.actions$
        .ofType(institutionActions.InstitutionActionTypes.GetInstitutions)
        .pipe(
          switchMap(() => {
            const institutions = this.getInstitutions();
            console.log(institutions);
            return this.getInstitutions();
          }),
          map((institutions: Institution[]) => {
            // return institutions;
            return {
              type: institutionActions.InstitutionActionTypes.GetInstitutionsSuccess,
              payload: institutions
            };
          })
        );
    

    希望能有帮助!