J4N
J4N

Reputation: 20697

How to return an observable that combines results of another observable?

The goal is to retrieve a document from firestore, and for each document, complete it with an array of documents coming another collection.

Firestore isn't supporting the "inclusion" of subcollection.

In my cases, I've a Test, which has a whole array of "TestResults". The name of the test results is the firebase ID.

So far, I've the following:

const result = this.firestore
         .doc<Test>(`tests/${testId}`)
         .valueChanges({ idField: 'id' })
         .pipe(
            switchMap((test) =>
               this.firestore
                  .collection<TestResult>(`tests/${test.id}/results`)
                  .valueChanges({ idField: 'name' })
                  .pipe
                  //How to assign my testResults[] to my current test
                  //And how to return a test?
                  ()
            )
         );

I guess I do a tap(results=>test.results =results), but then result would not be a Observable<Test>.

How would you achieve this? The same logic will be used to get all tests.

Thank you very much for your help

Upvotes: 1

Views: 48

Answers (1)

Amer
Amer

Reputation: 6706

Use map instead of tap and let it returns the test object after changing its results.

Try the following:

const result = this.firestore
  .doc<Test>(`tests/${testId}`)
  .valueChanges({ idField: 'id' })
  .pipe(
    switchMap(test =>
      this.firestore
        .collection<TestResult>(`tests/${test.id}/results`)
        .valueChanges({ idField: 'name' })
        .pipe(
          map(results => {
            test.results = results;
            return test;
          })
        )
    )
  );

Upvotes: 2

Related Questions