简体   繁体   English

为什么 concatMap 不能同时处理多个请求?

[英]Why concatMap does not work for multiple requests at once?

I have an array of objects data/ids received as parameter in the function where I should execute a post request for each element/id:我在 function 中有一个作为参数接收的对象数据/ID 数组,我应该在其中为每个元素/ID 执行一个发布请求:

fillProfile(users) {

    const requests = [];
    console.log( 'USERS.length:', users.length );
    requests.push( this.http.post( '/test/add', users[i] ) );

    for ( let i = 0; i < users.length; i++) {
        return this.http.post( '/test/add', users[i] ).pipe(
            map( (res) =>  {
                console.log( 'res: ', res );
                return res;
            }),
            catchError(err => {
                return throwError(err);
            })
        );
    }

It's working but it's not a good praxis and so fare I did search, it can be done via forkJoin or other operators.它正在工作,但它不是一个好的实践,所以我确实搜索过,它可以通过forkJoin或其他运算符来完成。 Have been trying these options/answers found in SO but unfortunately none of them did work.一直在尝试在 SO 中找到的这些选项/答案,但不幸的是它们都没有奏效。

One option I tried which doesn't work:我尝试过的一个选项不起作用:

 ....
 return from(requests2).pipe(
     concatMap((request) => request.pipe(
         delay(500),
         map( res => {
             // console.log( 'res: ', res );
             return res;
         })
    ))
);

Any idea how to execute multiple requests and also get response and error of each one separately in a better approach?知道如何执行多个请求并以更好的方法分别获得每个请求的响应和错误吗?

Fixed.固定的。 It was my mistake cause thinking in the wrong direction and also had a bug when creating array.这是我的错误导致思考方向错误,并且在创建数组时也有错误。 The way how it works now:它现在的工作方式:

in service:在役:

getArrayIds(users) {
    this.observables = [];
    for ( const i in users) {
        this.observables.push( this.http.post( '/test/add', users[i] ) );
    }
}


fillProfile(users): Observable<any> {
    return from(this.observables).pipe(
        concatMap((request) => request.pipe(
            delay(10),
            map( res => {
                return res;
            })
        ))
    );
}

in *.component.ts:在 *.component.ts 中:

....
public results$: BehaviorSubject<Array<any>> = new BehaviorSubject([]);

....
this.surveyService.answerSurveyQuestions(body).subscribe(res => {
     console.log( 'response: ', res );
     this.results$.next(this.results$.getValue().concat(res));
});

Can even output the results$ in the View ans debug all the response.甚至可以 output 中的结果 $查看并调试所有响应。 Thanks to this question and the answers there!感谢这个问题和那里的答案!

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

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