我有一个父可观察对象和两个子可观察对象,它们从父响应中获取trialId
并自行进行http调用。我尝试使用mergeMap
,但它给我错误,它不是一个函数。我该怎么办?
private _trialListPoll$ = timer(0, this.listRequestInterval).pipe(
this.trialDataService.getTrailForPatient(this.patientId).mergeMap(
(data) => {
if (data.result.length > 0) {
const trial = data.result[0] as TrialPhase;
this.trialId = trial.trialId;
this.trialStartDate = trial.startDate;
this.trialEndDate = trial.endDate;
this.trialData$.next(data.result[0]);
this.loadDailyQuestionaireAnswerData(this.trialId); // child which makes http call and being subscribed somewhere
this.loadStartEndQuestionaireData(this.trialId); // child which makes http call and being subscribed somewhere
} else {
this.trialStartDate = undefined;
this.trialEndDate = undefined;
this.trialData$.next(undefined);
}
this.isQuestionnaireInDateRange();
this.isLoadingTrial$.next(false);
}
),share());
答案 0 :(得分:0)
通常,您会像这样进行嵌套调用:
todosForUser$ = this.http.get<User>(`${this.userUrl}/${this.userName}`)
.pipe(
switchMap(user =>
this.http.get<ToDo[]>(`${this.todoUrl}?userId=${user.id}`)
)
);
在此示例中,我们通过用户名获取用户,然后使用switchMap
通过获取的用户ID获取相关数据。
对于多个请求,您可以执行以下操作:
可观察
dataForUser$ = this.http.get<User>(`${this.userUrl}/${this.userName}`)
.pipe(
switchMap(user =>
combineLatest([
of(user),
this.http.get<ToDo[]>(`${this.todoUrl}?userId=${user.id}`),
this.http.get<Post[]>(`${this.postUrl}?userId=${user.id}`)
])
),
map(([user, todos, posts]) => ({
name: user.name,
todos: todos,
posts: posts
}) as UserData)
);
数据集的接口
export interface UserData {
name: string;
posts: Post[];
todos: ToDo[];
}
此代码检索第一组数据(因此我们从用户名中获得了userId),然后使用combineLatest
组合每个流中的最新值。
我在这里有一个stackblitz示例:
https://stackblitz.com/edit/angular-todos-deborahk
希望这会有所帮助。