簡體   English   中英

將RXJS可觀察的結果合並為一個

[英]Combine RXJS observable results into one

我的數據庫中有兩個節點:

users: {user1: {uid: 'user1', name: "John"}, user2: {uid: 'user2', name: "Mario"}}
homework: {user1: {homeworkAnswer: "Sample answer"}}

有些用戶可能有功課,也可能沒有。

我想通過一次調用就獲得所有用戶的列表以及每個用戶的作業數據,然后進行訂閱。 實現這一目標的最佳方法是什么?

對於上面的示例,獲得的列表如下所示:

[{uid: 'user1', name: "John", homework: {homeworkAnswer: "Sample answer"}}, {uid: 'user2', name: "Mario"}]

這是我對usershomework兩個觀察值:

let usersObservable = this.af.getObservable(`users/`);
let hwObservable = this.af.getObservable(`homework/`);

基本上,您需要做兩件事,但是可能需要考慮一些細節。

  1. 從兩個可觀察對象獲取數據。
  2. 將數據轉換為所需的結果。

第一步可以通過使用forkJoin輕松實現。 forkJoin您可以傳入多個可觀察對象,並且所有可觀察對象完成后它將發出一個值。 重要提示: forkJoin僅在完成后發出。 如果您的數據來自商店或主題,則可能必須添加take(1)運算符,這樣它才能真正完成。

轉換部分也應該很容易。 我假設您要擁有用戶對象中存在的所有用戶,因此我們可以使用Object.keys遍歷現有用戶鍵,然后使用map轉換數據。

// Imports:
import { forkJoin } from 'rxjs';
import { take } from 'rxjs/operators';

// Step 1: Use fork join to get the result from both observables
forkJoin(
    // pipe(take(1)) is only needed if the observables don't complete.
    usersObservable.pipe(take(1)), 
    hwObservable.pipe(take(1))
)
    // Step 2: Transform the data.
    // We now need to map our both results. We want to return all
    // users and add the homework if available. So we can user
    // Object.keys to iterate over the existing user keys in your object.
    .pipe(map(([users, homeworkMap]) => Object.keys(users)
        // Now we can map the keys to the actual user objects
        // and merge them with the homework
        .map(userKey => {
            const user = users[userKey];
            const homework = homeworkMap[userKey];
            return {
                ...user,
                homework
            };
        })
    ))
    .subscribe(users => console.log('Users: ', users));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM