可观察数组的可观察对象?

问题描述 投票:1回答:1

我有一个Firestore文档,它有两个属性,它们都是Firestore数据库中其他地方的不同<Game>{}对象的ID数组。

有没有办法让我创建一个observable来流一个对象,该对象包含这些id所代表的项目的两个独立数组?

我不认为有一种方法可以只有一个单一的对象流,因为(一旦我订阅)我不知道哪个项属于哪个数组,因为数组大小不是常数。

我是观察者和rxjs的新手,并且不断阅读不同的运算符,但是如果我找不到解决方案的话,我会考虑重新调整我的数据。

现在,我在我的服务类中有这样的东西,但是当我订阅该函数时它不会像我期望的那样工作。

  getPlayerGames(uid: string) {
    return this._db.doc<PlayerGameSession>(`users/${uid}/mygamesession/games`).valueChanges().pipe(
      map(gameObj => {
        let combined1;
        let combined2;

        if (gameObj.prop1) {
          const prop1Streams = gameObj.prop1.map(
            gameId => this._db.doc<Game>(`games/${gameId}`).valueChanges()
          );

          combined1 = combineLatest(...prop1Streams);
        }

        if (gameObj.prop2) {
          const prop2Streams = gameObj.prop2.map(
            gameId => this._db.doc<Game>(`games/${gameId}`).valueChanges()
          );

          combined2 = combineLatest(...prop2Streams);
        }

        return combineLatest(combined1, combined2);

      }),
      switchMap(([c1, c2]) => of({ c1: c1, c2: c2 }))
    );
  }
angular rxjs google-cloud-firestore observable
1个回答
1
投票

如果要返回具有两个数组的对象的observable,并且需要组合数组observable所需的数据,则返回具有observable类型的两个属性的对象的observable,如下例所示:

const v1 = new BehaviorSubject('1')
const v2 = new BehaviorSubject('2')
const v3 = new BehaviorSubject('3')
const v4 = new BehaviorSubject('4')

const combined1 = combineLatest(v1, v2)
const combined2 = combineLatest(v3, v4)

const combined3 = combineLatest(combined1, combined2)

combined3
  .pipe(switchMap(([c1, c2]) => of({c1: c1, c2: c2})))
  .subscribe(console.log)

在这个例子中,我将四个observable组合成两个数组,然后将这些arraies组合成两个数组的组合对象

试试这段代码:

getPlayerGames(uid: string) {
    return this._db.doc<PlayerGameSession>(`users/${uid}/mygamesession/games`).valueChanges().pipe(
  switchMap(gameObj => {
    let combined1 = of([]);
    let combined2 = of([]);;

    if (gameObj.prop1) {
      const prop1Streams = gameObj.prop1.map(
        gameId => this._db.doc<Game>(`games/${gameId}`).valueChanges()
      );

      combined1 = combineLatest(...prop1Streams);
    }

    if (gameObj.prop2) {
      const prop2Streams = gameObj.prop2.map(
        gameId => this._db.doc<Game>(`games/${gameId}`).valueChanges()
      );

      combined2 = combineLatest(...prop2Streams);
    }

    return combineLatest(combined1, combined2)
       .pipe(switchMap(([c1, c2]) => of({c1: c1, c2: c2}))

  })
);

}

© www.soinside.com 2019 - 2024. All rights reserved.