在我的專案中,有時我想在用戶更改另一個串列中的選定值時更新串列中的可用選項。為此,我使用valueChanges了pipe運算子,switchMap如下所示:
this.form.controls.typeControl.valueChanges
.pipe(
switchMap((typeId: number) => {
return this.typesService.getProjectsByType(typeId);
}),
)
.subscribe((projects) => {
//...
});
現在我有一個問題,我需要一次執行兩個 http 請求來更新多個串列,而不僅僅是一個。當我嘗試添加第二個switchMap時,我得到error TS2345: Argument of type 'OperatorFunction<number, Project[]>' is not assignable to parameter of type 'OperatorFunction<any, number>'.以下是我嘗試執行此操作的方法:
this.form.controls.typeControl.valueChanges
.pipe(
switchMap((typeId: number) => {
return this.typesService.getProjectsByType(typeId);
}),
switchMap((typeId: number) => {
return this.typesService.getProgramsByType(typeId);
}),
)
.subscribe(([projects, programs]) => {
//...
});
如何在此處添加第二個 http 請求,以便處理兩個請求中接收到的資料subscribe?
uj5u.com熱心網友回復:
您可以使用combineLataest或forkJoin創建一個可觀察物件,該可觀察物件在其中任何一個源發出時發出:
this.form.controls.typeControl.valueChanges.pipe(
switchMap(typeId => combineLatest([
this.typesService.getProjectsByType(typeId),
this.typesService.getProgramsByType(typeId)
]))
)
.subscribe(([projects, programs]) => {
// ...
});
但是,如果這兩個資料(projectList 和 programList)彼此不相關,您可能會發現將它們定義為單獨的 observable 更方便:
private typeId$ = this.form.controls.typeControl.valueChanges;
projectList$ = this.typeId$.pipe(switchMap(id => this.typesService.getProjectsByType(id)));
programList$ = this.typeId$.pipe(switchMap(id => this.typesService.getProgramsByType(id)));
這可以為您提供更精細的控制,并允許您async更輕松地在模板中使用管道:
<h1> Projects </h1>
<ul>
<li *ngFor="let project of projectList$ | async">
{{ project.name }}
</li>
</ul>
<h1> Programs </h1>
<ul>
<li *ngFor="let program of programList$ | async">
{{ program.name }}
</li>
</ul>
uj5u.com熱心網友回復:
forkJoin 操作員可以在這里提供幫助,你可以這樣做:
this.form.controls.typeControl.valueChanges
.pipe(
switchMap((typeId: number) => {
return forkJoin([
this.typesService.getProjectsByType(typeId),
this.typesService.getProgramsByType(typeId)
])
})
)
.subscribe(([projects, programs]) => {
//...
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/455180.html
