简体   繁体   English

如何将可观察变量数组合并为具有相同返回类型的单个可观察变量

[英]How to merge an array of Observables into a single Observable of the same return type

What I am trying to achieve is push a few http request observables in an array and then combine all the responses and return with a single observable. 我要实现的目标是在数组中推送一些http请求的可观察对象,然后将所有响应组合在一起并返回一个可观察对象。

Since all the http requests resolve with the same type 'User', I just want to wait for all of them to resolve and then I can return a single observable with all Users from getUsers() function. 由于所有http请求都以相同的类型'User'进行解析,因此我只想等待它们全部解析,然后我可以从getUsers()函数返回一个包含所有Users的可观察对象。

I'm stuck at the return merge(observableRequests) part as I can't get the return type right and I'm not too versed in Rxjs functions. 我被困在return merge(observableRequests)部分,因为我无法正确获得返回类型,而且我不太熟悉Rxjs函数。

Here are my three related functions. 这是我的三个相关功能。

    getMyUser(): Observable<User> {
        return this.service.get(`${this._userPath}me`).pipe(
            map((serviceUser: any) => {
                return parseUser(serviceUser);
            }));
    }

    getUsers(): Observable<User[]> {
        return this.getMyUser()
            .pipe(switchMap((user: User) => {
                const activeProvidersIds = this._getActiveProvidersIds(user.providers);
                const observableRequests = activeProvidersIds.map((id: number) => this.getUserRequest(id));
                return merge(observableRequests);
            }));
    }

    getUserRequest(facDbk: number): Observable<User[]> {
        return this.service.get(`${this._providerPath}${facDbk}/users`).pipe(
            map((serviceUsers: any) => {
                return parseUsers(serviceUsers);
            })
        );
    }

Any help is appreciated. 任何帮助表示赞赏。

I guess you are looking for forkJoin : 我猜你在找forkJoin

When all observables complete, emit the last emitted value from each.

https://www.learnrxjs.io/operators/combination/forkjoin.html https://www.learnrxjs.io/operators/combination/forkjoin.html

Here is an example that may helps you: 这是一个可以帮助您的示例:

https://stackblitz.com/edit/angular-seuqh5 https://stackblitz.com/edit/angular-seuqh5

ForkJoin will work in your use case, you can follow this code ForkJoin将在您的用例中工作,您可以遵循此代码

import { Observable, of, forkJoin } from 'rxjs'; 
import { map } from 'rxjs/operators';

interface user {
  id : string;
  name: string;
}

// mimicking api requests
const httpRequest = (num): Observable<user> =>{
  return Observable.create((observer)=>{
    const [id,name] = [`id-${num}`,`name-${num}`];
    setTimeout(()=>{
     observer.next({id,name});
     observer.complete();
    },num*1000);
  });
}

//push array of request observables and return single observable
// you can push any number of request here 
const makeRequestInParallel = ():Observable<user> =>{
  const reqs:Observable<user>[] = [httpRequest(1),httpRequest(2),httpRequest(3)];
  return forkJoin(...reqs);
}


makeRequestInParallel().subscribe((result)=>{
  console.log(result);
});


click stablitz-link 单击稳定链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM