我有一个api,可以给我返回Array<string>
的ID,并给出了原始ID(一对多)。我需要对每个ID发出一个HTTP请求,以从api取回关联的数据。我无法弄清楚如何使用Observable<string[]>
并将其映射到Observable<DataType[]>
。
我希望保持原始的可观察性,并尽可能使用运算符获得所需的结果。
在这种情况下,使用map
运算符无法工作,原因是可观察到的唯一项是数组。
这是一些示例代码,与我尝试的实现类似。
getIds = (originalId: string) => {
return this.http.get<string[]>(url);
}
getDataFromIds = (originalId: string): Observable<DataType[]> => {
const ids$ = this.getIds(originalId);
// Make http calls for each of the items in the array.
result = ids$.pipe();
return result;
}
答案 0 :(得分:3)
这通常是switchMap运算符的用例,您可以在内部观察到forkjoin运算符。
getIds = (originalId: string) => {
return this.http.get<string[]>(url);
}
getDataFromIds = (originalId: string): Observable<DataType[]> => {
const ids$ = this.getIds(originalId);
// Make http calls for each of the items in the array.
result = ids$.pipe(switchmap(ids => forkJoin(ids.map(id => this.getId(id))));
// map the array of ids into an array of Observable<DataType>, forkjoin them and switch into it.
return result;
}
这假定getIds()调用将产生一个字符串ID列表,并且您具有一些getId()函数,该函数采用字符串ID并返回可观察的DataType
答案 1 :(得分:0)
您可以尝试以下方法:
Dim ctrl As Control
Dim fr1 As Boolean
For Each ctrl In Me.Controls
If TypeOf ctrl Is MSForms.OptionButton Then
Select Case ctrl.Parent.Name
Case "Frame1"
If ctrl.Value = True Then fr1 = True
End Select
End If
Next ctrl
If fr1 = False Then MsgBox "No selection for option buttons in Frame1"
Exit Sub
ids$.pipe(
switchMap(ids => //you can swap switchMap with any *Map operator: https://www.learnrxjs.io/operators/transformation/
forkJoin(...ids.map(id => //you swap forkJoin with any comb. operator: https://www.learnrxjs.io/operators/combination/
from(Promise.resolve({ id })).pipe(
map(res => res.id),
catchError(err => of(err)))))));
的进口应该从from, forkJoin
进口,而其他所有东西都从rxjs
进口
rxjs/operators
将捕获任何抛出的未处理错误。