首页 > 解决方案 > 角。从 switchMap 内的订阅中获取价值

问题描述

我有用户个人资料编辑表格。如果用户上传照片,我需要将其上传到后端,获取图片名称作为响应(例如timestamp_name.jpg)并将此名称与其他提供的属性一起保存,例如姓名、电子邮件等。在存储效果中,我尝试通过以下方式进行操作:

@Effect()
  profileUpdated$ = this.actions$.pipe(
    ofType<ProfileUpdated>(UserActionTypes.ProfileUpdated),
    map(action => action.payload),
    switchMap(payload => {
      if (!!payload.picture) {
        this.uploadResource.image(payload.picture.files[0]).subscribe((res) => payload.picture = res);
      }
      return this.userResource.updateMyself({user: payload});
    }),
  );

但是属性图片没有改变,导致它在订阅中。是否有另一种解决方案来实现它?

标签: angularrxjsngrx

解决方案


您检测到subscribe问题是正确的。Asubscribe永远不应出现在运算符中。只有profileUpdated$需要订阅的最终消费者。以下是您的代码的修改版本:

profileUpdated$ = this.actions$.pipe(
    ofType<ProfileUpdated>(UserActionTypes.ProfileUpdated),
    map(action => action.payload),
   // Upload image if needed
    switchMap(payload => {
      if (!!payload.picture) {
        return this.uploadResource.image(payload.picture.files[0]).pipe(
          map(res => {
             payload.picture = res;
             return payload;
          })
        );
      } else {
        // A switchMap operator must always return an Observable,
        // so in the case where no image needs to be uploaded
        // we simply return the original payload as an Observable.
        return of(payload);
      }
    }),
    // Update profile information
    switchMap(payload => this.userResource.updateMyself({user: payload}))
  );

推荐阅读