Angular(4/5/6/7/8)重构在订阅代码中订阅

时间:2019-08-21 09:53:10

标签: angular angular7 angular8 subscribe

嗨,我想简化以下代码。在以下情况下很难应用switchMap,因为我在第二订阅方法中使用了forEach循环。有什么更好的编码方式呢?感谢您的帮助!

UICollectionViewCell

1 个答案:

答案 0 :(得分:1)

更好的方法可能是利用 pipable 运算符,并将arraymergeAll展平。

this.profileService
  .listProfileActivities(this.authService.profileId)
  .pipe(
    mergeAll(),
    filter(activity =>
        activity.type === 'favorite' &&
        activity.to === this.authService.profileId
    ),
    mergeMap(activity => 
        this.profileService.readProfile(activity.from)
                           .pipe(map(profile => ({ profile, activity })))
    ),
    map(result => ({
        profile: result.profile,
        profileId: result.profile.id,
        imageId: result.profile.imageID,
        name: result.profile.name,
        timeago: new Date(result.activity.at)
    }))
  ).subscribe({
    next: notification => this.notifications.push(notification)
  });