有角度的。从switchMap内的订阅中获取价值

时间:2018-10-24 12:32:22

标签: angular rxjs ngrx

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

但是属性图片没有改变,导致它在订阅中。有没有其他解决方案可以实现?

1 个答案:

答案 0 :(得分:2)

您正确地检测到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}))
  );