在Angular 2+中,可以使用RxJS的flatMap
操作符来处理嵌套订阅的对象数组。下面是一个示例代码:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { flatMap } from 'rxjs/operators';
@Component({
selector: 'app-example',
template: `
-
{{ item.name }}
`,
})
export class ExampleComponent implements OnInit {
items$: Observable;
constructor(private http: HttpClient) {}
ngOnInit() {
this.items$ = this.http.get('https://api.example.com/items').pipe(
flatMap(items => {
// 使用flatMap操作符嵌套订阅
return items.map(item => this.http.get(`https://api.example.com/item/${item.id}`));
})
);
}
}
在上面的示例代码中,我们使用HttpClient
进行HTTP请求,获取到了一个对象数组items
。然后,我们使用flatMap
操作符来处理这个数组,返回一个新的Observable。在flatMap
操作符中,我们使用map
函数来遍历items
数组,并使用this.http.get
发起嵌套的HTTP请求,返回一个新的Observable。最后,我们将这个新的Observable赋值给items$
属性,以供模板中使用。
注意:在使用这种嵌套订阅的方式时,需要确保内部的HTTP请求都返回一个Observable。