简体   繁体   English

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

[英]Angular. Get value from subscription inside switchMap

I have user profile editing form. 我有用户个人资料编辑表。 If user upload photo i need to upload it to backend, get picture name in response (timestamp_name.jpg for example) and save this name with other provided properties, such as name, email and so on. 如果用户上传照片,我需要将其上传到后端,请在响应中获取图片名称(例如timestamp_name.jpg),并使用其他提供的属性(例如名称,电子邮件等)保存该名称。 In store effect i have tried to do it in next way: 在存储效果中,我尝试过以下方式:

@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});
    }),
  );

But property picture did not changed, cause it inside subscription. 但是属性图片没有改变,导致它在订阅内。 Is there another solution to achieve it? 还有其他解决方案吗?

You are correct in detecting that the subscribe is the problem. 您正确地检测到subscribe是问题。 A subscribe should never appear in an operator. subscribe不应出现在运算符中。 Only the end consumer of profileUpdated$ needs to subscribe. 只有profileUpdated$的最终用户需要订阅。 Below is a modified version of your code: 下面是代码的修改版本:

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}))
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM