rxjs ऑपरेटरों, किसी एकल ऑब्जेक्ट में नेस्टेड डेटा कैसे लौटाएं?

Nov 30 2020

मैं नेक्सस डेटा को rxjs तरीके से लाने का एक साफ तरीका खोजने में असमर्थ हूं।

एक अवलोकन योग्य सभी उपयोगकर्ताओं को लौटाने और एक अवलोकन योग्य सभी पदों को एक उपयोगकर्ता आईडी दिया गया है।

getUsers(): Observable<User[]>

तथा

getPosts(id: string): Observable<[]>

मैं अपने पोस्ट सहित उपयोगकर्ताओं की सूची कैसे लौटाऊंगा?

फिलहाल मैं 2 नेस्टेड सब्सक्रिप्शन का उपयोग करके डेटा तैयार करता हूं।

nestedFetch() {
  this.service.getUsers()
  .subscribe(
    res => {
      res.forEach((user) => {
        this.service.getPosts(user.Id).subscribe(
          posts => {
            user.posts = posts;
            this.users.push(user);
          },
          err => console.log('something went wrong: ' + err)
        )
      })
    },
    err => console.log('something went wrong: ' + err)
  );
}

मैं नहीं बल्कि ऑपरेटरों को कुछ इस तरह का उपयोग करेगा। लेकिन मैं उपयोगकर्ताओं को उनके पदों सहित कैसे वापस कर सकता हूं?

nestedFetch() {
  this.service.getUsers().pipe(
    map(users => users.map(u => this.membership.getPosts(u.id))),
    mergeMap(posts => forkJoin(posts))
  ).subscribe(
    res => this.posts = posts, //returns only posts but not users
    err => console.log('something went wrong: ' + err)
  )
}

जवाब

2 MoxxiManagarm Nov 30 2020 at 19:19

एक आंतरिक पाइप उपयोगकर्ता को उसके पदों द्वारा विस्तारित करने में मदद करता है।

this.service.getUsers().pipe(
  switchMap(users => {
    const postsRequests$ = this.users.map(user => this.service.getPosts(user.id).pipe( // example for a error catch which would lead to an empty array not breaking the forkJoin // catchError(err => of([])), map(posts => ({ ...user, posts })), )); return forkJoin(postsRequests$);
  }),
).subscribe(/* ... */);