如果你想要在Angular中嵌套使用可观察对象,可以使用switchMap
操作符来实现。下面是一个示例:
在你的组件中,首先导入必要的库和服务:
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { DataService } from 'path/to/data.service';
@Component({
selector: 'app-my-component',
template: `
{{ item }}
`
})
export class MyComponent {
nestedItems$: Observable;
constructor(private dataService: DataService) {}
ngOnInit() {
this.nestedItems$ = this.dataService.getTopItems().pipe(
switchMap(topItems => {
return this.dataService.getNestedItems(topItems);
})
);
}
}
在上面的示例中,DataService
是一个自定义的服务,用于从后端获取数据。getTopItems
方法返回一个可观察对象,它表示顶层的项目。getNestedItems
方法接收顶层项目作为参数,并返回一个可观察对象,表示与每个顶层项目相关联的嵌套项目。
在ngOnInit
生命周期钩子中,我们使用switchMap
操作符来订阅getTopItems
方法返回的可观察对象,并在每次收到新的顶层项目时,取消订阅之前的嵌套项目,并重新订阅新的嵌套项目。
在模板中,我们使用async
管道来订阅nestedItems$
可观察对象,并在每次收到新的嵌套项目时更新UI。