【问题标题】:Wait end of two subscribe to make an operation等待两个订阅结束进行操作
【发布时间】:2026-01-26 14:30:01
【问题描述】:

我有两个这样的订阅:

this.birthdays = await this.birthdaySP.getBirthdays();
this.birthdays.subscribe(groups => {
    const allBirthdayT = [];
    groups.map(c => {
      allBirthdayT.push({
        key: c.payload.key, 
        ...c.payload.val()
      })
    })

    console.log(allBirthdayT);
});

this.birthdaysInGroups = await this.birthdaySP.getBirthdaysInGroups();
this.birthdaysInGroups.subscribe(groups => {
    const allBirthdayB = [];
    groups.map(c => {
      c.birthdays.subscribe(d => {
        d.map(e => {
          allBirthdayB.push(e);
        })
      })
    })

    console.log(allBirthdayB);
});

我想等待这两个订阅结束来比较 allBirthdayB 和 allBirthdayT 数组(我在两个 console.log 中接收数据)。

this.birthdaySP.getBirthdays()this.birthdaySP.getBirthdaysInGroups() 是两个从 firebase 接收数据的 observable。

第一个 Observable 是这样的:

async getBirthdays() {
   const user = await this.authSP.getUserInfo();
   return this.angularFire.list('birthdays', ref => ref.orderByChild('creator_user_id').equalTo(user.uid)).snapshotChanges();
}

我尝试使用 forkJoin,但我不知道如何使用它来解决这个问题

有什么建议吗?

【问题讨论】:

    标签: javascript angular firebase firebase-realtime-database angularfire2


    【解决方案1】:

    您可以使用combineLatest() 函数。

    例子:

    combineLatest(observable1$, observable2$)
        .subscribe(([observable1, observable2]) => {
            console.log(observable1, observable2);
        });
    

    【讨论】: