【问题标题】:Angular. Get value from subscription inside switchMap角。从 switchMap 内的订阅中获取价值
【发布时间】:2019-03-28 20:58:36
【问题描述】:

我有用户个人资料编辑表单。如果用户上传照片,我需要将其上传到后端,获取图片名称作为响应(例如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});
    }),
  );

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

【问题讨论】:

    标签: angular rxjs ngrx


    【解决方案1】:

    您检测到subscribe 是问题是正确的。 subscribe 永远不应出现在运算符中。只有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}))
      );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-02
      • 2018-12-22
      • 1970-01-01
      • 2019-06-06
      • 2020-10-09
      • 1970-01-01
      • 2019-01-21
      • 2020-04-05
      相关资源
      最近更新 更多