Как создать единый массив с Rx js? - PullRequest
0 голосов
/ 27 мая 2020

Я хочу создать единый массив объектов из ngrx selectors.

Возникающая проблема заключается в том, что он создает массив объектов только для последнего элемента массива и не для всех.

МОЙ КОД:

this.userSelectorsService.usersFriends.subscribe(users => {
        users.forEach(user =>
            combineLatest([this.chatSelectorsService.getFriendLatestMessageById(user.id), this.chatSelectorsService.getTotalUnreadMessagesFriendById(user.id)])
                .pipe(takeWhile(chatSelectors => chatSelectors[1] > 0))
                .subscribe(chatSelectors => {
                    console.log(chatSelectors);
                    this.lastMessages$.next({
                        user,
                        latestMessage: {
                            ...chatSelectors[0],
                            isNewLastMessage: user.isClicked,
                        },
                    });
                })
        );
    });

РЕЗУЛЬТАТ: enter image description here

Что я использую sh:

[
    {
        "id":"1",
        "text":"In a world where changes are taking place quickly, the only strategy that will guarantee failure is to not take risks.",
        "time":"10:20",
        "isMain":false,
        "isRead":false,
        "isNewLastMessage":false
    },
    {
        "id":"2",
        "text":"tst",
        "time":"10:20",
        "isMain":false,
        "isRead":false,
        "isNewLastMessage":false
    },
    {
        "id":"3",
        "text":"tst 3",
        "time":"10:20",
        "isMain":false,
        "isRead":false,
        "isNewLastMessage":false
    }
]

1 Ответ

1 голос
/ 28 мая 2020

попробуй построить трубы, и честно говоря слишком много неизвестного в твоем вопросе.

this.userSelectorsService.usersFriends.pipe(
  switchMap(users => {
    const set = [];
    for (const user of users) {
      // creating a set of data per user.
      set.push(combineLatest([
        of(user),
        this.chatSelectorsService.getFriendLatestMessageById(user.id),
        this.chatSelectorsService.getTotalUnreadMessagesFriendById(user.id),
      ]).pipe(
        takeWhile(([user, messageId, total] => total > 0),
        // mapping data to the structure we need
        map(([user, messageId, total]) => ({
          id: user.id,
          text: "tst",
          time: "10:20",
          isMain: false,
          isRead: false,
          isNewLastMessage: user.isClicked,
        })),
      ));
    }
    // or combineLatest(set), or combineAll(set), depends on your needs.
    return merge(...set);
  }),
  // toArray(), // in case of you want an array of all emits.
// forwarding data to the this.lastMessages$.
).subscribe(formattedData => this.lastMessages$.next(formattedData));
...