根据我想要构建forkJoin()方法的函数的参数.
例如:
如果parameter1为空=>不要在forkJoin()中放入http请求
如果parameter2为空=>不要在forkJoin()中放入http请求
码:
getAllByIds(parameter1: any, parameter2: any) { let itemList = new Array(); return Observable.forkJoin( this.http.get('rest/fillin/ids/' + parameter1) // don't put this request for parameter1 if it is empty .map((res: Response) => res.json()), this.http.get('rest/textitem/ids/' + parameter2) // don't put this request for parameter2 if it is empty .map((res:Response) => res.json()) ).map( data => { itemList.push(data[0]); itemList.push(data[1]); return itemList; } ); }
那么,是否有可能像这样建立forkJoin()?
实际上,这取决于您跳过某些HTTP请求时期望获得的内容.
输出是否应forkJoin()
包含null
值或完全忽略它?
function mockHTTPRequest(id) { return Observable.of(id).delay(100); } let parameter1 = 'a'; let parameter2 = false; let sources = []; if (parameter1) { sources.push(mockHTTPRequest('rest/fillin/ids/' + parameter1)); } if (parameter2) { sources.push(mockHTTPRequest('rest/textitem/ids/' + parameter2)); } Observable.forkJoin(...sources) .map(data => { console.log(data.length); return data; }) .subscribe(values => console.log(values));
查看现场演示:https://jsbin.com/qorulel/5/edit?js,console
如果parameter1
或者parameter2
为假,此解决方案不会创建源Observable .请注意,这console.log(data.length)
可以从0
以2
取决于parameterX
值.
或者您可以创建Observable.of(null)
而不是HTTP请求.
function mockHTTPRequest(id) { return Observable.of(id).delay(100); } let parameter1 = 'a'; let parameter2 = false; let sources = [ parameter1 ? mockHTTPRequest('rest/fillin/ids/' + parameter1) : Observable.of(null), parameter2 ? mockHTTPRequest('rest/textitem/ids/' + parameter2) : Observable.of(null) ]; Observable.forkJoin(...sources) .map(data => { console.log(data.length); return data; }) .subscribe(values => console.log(values));
查看现场演示:https://jsbin.com/caheno/5/edit?js,console
现在输出总是2个值.其中一些是null
.