【问题标题】:Angular firebase inner join using switch map使用切换映射的角度 Firebase 内部连接
【发布时间】:2020-09-02 07:42:12
【问题描述】:

我正在尝试从 firebase 数据库中获取所有订单,然后从订单中使用 customerId 获取有关客户的详细信息。 这是我的数据库架构:

订单:
客户
客户:
名称
姓氏

我的html模板:

  <h2>Raw Data</h2>
  <pre>{{rawData | async | json}}</pre>

以下代码返回ERROR TypeError: "cyclic object value"

  constructor(public db: AngularFireDatabase) {
    this.rawData = db.list('/orders').valueChanges().pipe(
      switchMap(orders => { const customerIds = uniq(orders.map((ord: Order) => ord.customer));
      return customerIds.map(customerId => db.object('customers/' + customerId + '/').valueChanges());} )
    );
  }

但是,当我尝试只返回一个与第一个订单相关的客户时,使用以下代码:

  constructor(public db: AngularFireDatabase) {
    this.rawData = db.list('/orders').valueChanges().pipe(
      switchMap(orders => { const customerIds = uniq(orders.map((ord: Order) => ord.customer));
      return db.object('customers/' + customerIds[0] + '/').valueChanges();} )
    );
  }

我收到了想要的输出。 为什么在地图中获取对我不起作用?我需要进一步处理地图的输出吗? 理想情况下,我希望有这样的输出

{
order_param = order_value
customer = {customer_param = customer_value }
}

我是 Angular 和 rxjs 的初学者,我试图关注这篇文章:
https://medium.com/@joaqcid/how-to-inner-join-data-from-multiple-collections-on-angular-firebase-bfd04f6b36b7

【问题讨论】:

    标签: angular database typescript rxjs angularfire


    【解决方案1】:

    发生这种情况是因为您返回了一个流数组但没有订阅它们。为此,您可以使用mergeAll

    如文档所述,mergeAll subscribes to an Observable that emits Observables. Each time it observes one of these emitted inner Observables, it subscribes to that and delivers all the values from the inner Observable on the output Observable.

    const getOrders$ = db.list('/orders').valueChanges();
    const getCustomerChangesById = customerId => db.object('customers/' + customerId + '/').valueChanges()
    
    constructor(public db: AngularFireDatabase) {
      this.rawData = getOrders.pipe(
        switchMap(orders => { 
          const customerIds = uniq(orders.map((ord: Order) => ord.customer));
          return customerIds.map(getCustomerChangesById);
        }),
        mergeAll(),
      );
    }
    

    【讨论】:

    • 谢谢,它就像魅力一样。我怎么知道我返回了流数组?在我的工作案例中,它是否因为只返回一个流而起作用?
    • 不客气,第一个问题:您可以使用运算符tapswitchMap 之后记录流的当前值,例如tap(console.log),第二个问题:是的,我想就是这样。
    猜你喜欢
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多