Chr*_*ris 6 rxjs angular-pipe angular switchmap angular12
在我的项目中,当用户更改另一个列表中的选定值时,我有时希望更新列表中的可用选项。为此,我使用了valueChanges运算符pipe,switchMap如下所示:
this.form.controls.typeControl.valueChanges
.pipe(
switchMap((typeId: number) => {
return this.typesService.getProjectsByType(typeId);
}),
)
.subscribe((projects) => {
//...
});
Run Code Online (Sandbox Code Playgroud)
现在我遇到的问题是,我需要一次执行两个 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]) => {
//...
});
Run Code Online (Sandbox Code Playgroud)
如何在此处添加第二个 http 请求,以便我可以处理 中两个请求收到的数据subscribe?
Biz*_*Bob 11
您可以使用combineLataestorforkJoin创建一个可观察对象,当它的任何一个源发出时,该可观察对象会发出:
this.form.controls.typeControl.valueChanges.pipe(
switchMap(typeId => combineLatest([
this.typesService.getProjectsByType(typeId),
this.typesService.getProgramsByType(typeId)
]))
)
.subscribe(([projects, programs]) => {
// ...
});
Run Code Online (Sandbox Code Playgroud)
但是,如果这两条数据(projectList和programList)彼此不相关,您可能会发现将它们定义为单独的可观察量更方便:
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)));
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13571 次 |
| 最近记录: |