我正在尝试用mergeMap和forkJoin有条件地执行5个并行的http请求。对我来说,只有第一个api会被执行,其余的api不会触发。
我的函数将执行第一个api,如果它返回状态为'NOT_FOUND',那么我需要执行另外5个api,并需要返回最终结果。如果我得到的状态不同于'NOT_FOUND',只需要从第一个http请求中返回observable。我尝试了不同的选项,但似乎都不起作用。在共享代码下面,我得到了"ERROR TypeError: Unable to get property 'map‘of undefined or null reference“
public myPostWrapper( url, body, flag): Observable<any> {
return this.http.post( url, body, { headers: this.headers } )
.map(( out: any ) => {
console.log( 'out', JSON.stringify( out ) );
this.result = out;
} )
.mergeMap(( response: any ) => {
console.log( 'response-inside', JSON.stringify( response ) );
if ( this.result.status === 'NOT_FOUND' ) {
return Observable.forkJoin(
response.map(( resp: any ) => {
return this.http.post(url, body, { headers: this.headers })
.map(( res: any ) => {
const section: any = res;
return section;
} );
} ),
response.map(( resp: any ) => {
return this.http.post(url, body, { headers: this.headers })
.map(( res: any ) => {
const section: any = res;
return section;
} );
} )
);
} else {
return Observable.of( this.result );
}
} )
.catch(( error: any ) => Observable.throw( error || 'Server error' )
);}
任何帮助/指导都将不胜感激。注意:我正在使用Rxjs 5.52和Angular 5
发布于 2018-08-01 16:38:37
在设置this.result的第一个map中,不返回任何内容。这意味着,链的以下部分将在undefined上运行。在第一个map操作中添加return out;,这应该可以解决您的问题。
...
return this.http.post( url, body, { headers: this.headers } )
.map(( out: any ) => {
console.log( 'out', JSON.stringify( out ) );
this.result = out;
return out; // <--- This return here
} )
...您可以选择将mergeMap中出现的所有response替换为this.result。
https://stackoverflow.com/questions/51628761
复制相似问题