【问题标题】:Angularfire2 How to use AngularFireList to retrieve one itemAngularfire2 如何使用 AngularFireList 检索一项
【发布时间】:2020-05-23 09:08:08
【问题描述】:

在我使用 angularfire2 的 Angular 应用程序中,我提供了获取和存储订单集合的服务。我将它们存储在 AngularFireList 中并使用以下方法获取它们:

db.list('items').valueChanges();

但是,在我的组件中,我需要从另一个位置获取订单和客户数据,我已经设法做到了,但是我在我的服务中使用了另一个 Observable 变量来存储连接数据 - 是否希望设计有两个集合在服务中存储部分相同的数据(纯订单数据对我来说似乎是重复的)?

第二个问题,如何从我的服务中的订单集合(AngularFireList 类型)中仅获取一个订单?我不想发出另一个请求,因为我已经在服务中获取了所有数据,但是当我尝试发出时:

valueChange().pipe(filter(order => { order.id == desiredId };), first()) 

我收到 observable,它只解析为带有值的数组,没有键。 如何管理?

如果有一些设计模式可以解决这种情况,我想知道它们。

【问题讨论】:

    标签: angular firebase rxjs angularfire2


    【解决方案1】:

    1) - 是的,这是设计使然,您有流(Observables),您可以根据需要组合它们以获得所需的行为,目标是正确组合它们以避免意外行为。

    例如,当服务触发订阅的后端并且您不希望添加 shareReplay(1) 以返回最新的已知值而不是实际请求时。

    2) 你需要稍微修改一下你的代码。

    sharedValueChange$ = valueChange().pipe(
      shareReplay(1),
    );
    
    // now these 2 will trigger only one valueChange() and share its emits.
    
    allOrderChanges$ = sharedValueChange$.pipe(
      // some logic without a filter
    );
    
    desiredOrderChanges$ = sharedValueChange$.pipe(
      filter(order => order.id === desiredId),
      // first(), // if you don't want to receive its updates anymore.
    );
    
    desiredOrderChanges$.subscribe(); // doesn't trigger an extra time valueChange() 
    desiredOrderChanges$.subscribe(); // doesn't trigger an extra time valueChange() 
    desiredOrderChanges$.subscribe(); // doesn't trigger an extra time valueChange() 
    

    3) 要调试解决方案,请在filter 之后添加tap(console.log) 并将输出放入您的问题中。

    【讨论】:

    • 感谢您的评论! ShareReplay 在这里做了这件事 :) 用 tap 调试后,我能够解决第三点,因此不需要进一步的帮助。
    猜你喜欢
    • 2019-03-30
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    相关资源
    最近更新 更多