简体   繁体   English

Angular RxJs 可观察到的 stream 合并数据

[英]Angular RxJs Observable stream merge data

I'm trying to refactor my Angular code to be more "reactive"我正在尝试重构我的 Angular 代码,使其更具“反应性”

I have data returned from an Observable which retreives account data account$ into an object for example:我有从 Observable 返回的数据,它将帐户数据 account$ 检索到 object 中,例如:

{
 accountid: "123435", 
 name: 'bob', 
 customerId: "AR4533" 
 ..etc}

I also want to retreive payment data from another method call and merge it into the account object data:我还想从另一个方法调用中检索付款数据并将其合并到帐户 object 数据中:

{
 paymentId: "13434", 
 paymentName:"pay1" 
 ..etc}

The payment data needs a customerId parameter which is in the parent account data.支付数据需要一个 customerId 参数,该参数位于父帐户数据中。

I've managed to pass this data through from the first observable using mergeMap however the resulting output is giving me the the payment data only, I want to have the account object with the payment data added within it as the output.我已经设法使用 mergeMap 从第一个 observable 传递这些数据,但是生成的 output 只给了我付款数据,我希望拥有 object 帐户,其中添加了付款数据为 Z78E6221F6393D13CE5D8668。 Like so:像这样:

{
 accountid: "123435", 
 name: 'bob', 
 paymentData: {
    paymentId: "13434", 
    paymentName:"pay1" ..etc
   }
}
account$ = this.http.get<IAccountResponse>('account')
    .pipe(
      map(data => data.data),
      mergeMap(data => this.http.get<any>(`payment/subscription?customer=${data.stripe.customerId}`)),
      tap(data => console.log('PIPE:account', data))
    )

I know mergeMap does replace the data in the stream but is there a way to make the data merge into the current stream data object?我知道 mergeMap 确实替换了 stream 中的数据,但是有没有办法让数据合并到当前的 stream 数据 object 中?

This can be solved by creating a closure :这可以通过创建闭包来解决:

account$ = this.http.get<IAccountResponse>('account')
    .pipe(
      map(data => data.data),
      mergeMap(
        data => this.http.get<any>(`payment/subscription?customer=${data.stripe.customerId}`).pipe(
          map(paymentData => ({ ...data, paymentData }))
        )
      ),
      tap(data => console.log('PIPE:account', data))
    )

I would use combineLatest in the mergeMap to get a handle on the accountData.我会在mergeMap combineLatest获取 accountData 的句柄。

import { combineLatest, of } from 'rxjs';

account$ = his.http.get<IAccountResponse>('account')
    .pipe(
      map(data => data.data),
      mergeMap(data => combineLatest(
        of(data.data),
        this.http.get<any>(`payment/subscription?customer=${data.stripe.customerId}`),
      )),
      map(([accountData, customerData]) => {
        return {
          acountid: accountData.accountid,
          name: accountData.name,
          paymentData: {
            paymentId: customerData.paymentId,
            paymentName: customerData.paymentName,
          }
        };
      }),
      tap(data => console.log(data)),
    )

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

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