rxjs with multiple forkjoin when doing http requests

后端 未结 1 1599
说谎
说谎 2021-01-16 11:41

I am doing some http requests and use rxjs for successfull notification of the result:

  getReportings(departmentId: number): Observable {
                


        
相关标签:
1条回答
  • 2021-01-16 12:04

    You could extend your stream using switchMap, like this:

    getReportings(departmentId: number): Observable<any> {
        return Observable.forkJoin(
            this.http.get('/api/members/' + departmentId).map(res => res.json()),
            this.http.get('/api/reports/' + departmentId).map(res => res.json())
        ).switchMap((result: [any[], any[]]) => {
            let members: any[] = result[0];
            let reports: any[] = result[1];
            let allNewStreams: Observable<any>[] = [
                Observable.of(members),
                Observable.of(reports)
            ];
            // do your stuff and push new streams to array...
            if (foo) { // for each additional request
                let reportId: string | number = reports[0].id; // or however you retrieve the reportId
                allNewStreams.push(
                    this.http.get('some/api/ + bar)
                        .map(res => res.json())
                        .map(data => ({reportId, data})); // so your final object will look like this: {reportId: "d38f68989af87d987f8", data: {...}}
                );
            }
    
            return Observable.forkJoin(allNewStreams); // will contain members, reports + 4-6 other results in an array [members[], reports[], ...other stuff]
        });
    }
    

    This should do it, it's more like an "old-style-logic-hammer" approach - in case you are looking for it: There might be a more elegant way to solve this by using other operators, but that is hard to say without knowing the full data and all logic.

    0 讨论(0)
提交回复
热议问题