【问题标题】:Fetching value from subscribed Observable with dynamic variable使用动态变量从订阅的 Observable 中获取值
【发布时间】:2019-05-26 19:08:45
【问题描述】:

我正在学习 Observables 如何通过 Angular 和 Google Firestore 工作。

this.allinvoicesCollection = this.afs.collection('clients').doc(this.clientId).collection('inbox').valueChanges();
    this.allinvoicesCollection.subscribe(val => {
      this.fileUrl = val[this.currentIndex].downloadURL;
    })

我正在使用上面的代码获取 fileUrl。

我想在变量“this.currentIndex”发生变化时更新fileUrl,但是上面的代码显然没有实现这一点。

我知道这只会在集合中的文档发生更改时触发。检测到“this.currentIndex”的变化时如何触发它?我应该提一下,“this.currentIndex”不是 Observable,只是用户更改的简单数字变量。

【问题讨论】:

    标签: angular google-cloud-firestore observable


    【解决方案1】:

    将当前索引设为Subject,您可以轻松检测到更改。

    currentIndex= new Subject<number>();
    

    然后当它发生变化时,您可以推送新数据。假设它在按钮 clik 上发生变化,或者如果它是输入控件,则可能在 keyup 上可以推送更新的索引。

    onIndexChange(id:number){
        this.currentIndex.next(id);
    }
    

    第二部分订阅allinvoicesCollection 时使用flatMap。 您可以查看this 答案以了解如何进行嵌套订阅。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 2023-04-02
      • 1970-01-01
      • 2019-05-29
      相关资源
      最近更新 更多