我有一个基于 Angular 的应用程序正在向服务器发出 RESTful 请求,该服务器的响应是表示以下类型的对象列表的 JSON 流:
export interface Personal {
theAddress: string;
theCity: string;
theState: String;
theCountry: string;
emailAddress: string;
}
我的组件中的代码使用 HttpClient GET 请求获取数据以放入 Observable:
people$: Observable<Personal[]>;
...
ngOnInit() {
this.people$ = this.http
.get<Personal[]>("/people/get")
.map(data => _.values(data))
.do(console.log);
}
由于各种原因,我想提取 Observable 的内容并将它们放入一个 people 对象数组中。在阅读了 Internet 上的各种文档后,我意识到要提取接收到的数据,我需要以某种方式在 Observable 上使用订阅方法。不幸的是,我不清楚具体如何执行此操作。
有人可以帮忙吗?如何将 Observable 接收到的对象提取到数组中?
最佳答案
如果您需要数组中的值,则不需要 people$
成为可观察的。只需这样做:
import 'rxjs/add/operator/map';
...
people: Personal[];
...
ngOnInit() {
// Let's get rid of lodash for the mapping thing
this.http.get<Map<string, Personal>>('/people/get')
.map(data => Object.keys(data).map(key => data[key]))
.subscribe((people: Personal[]) => this.people = people);
}
顺便说一句,您似乎使用的是过时的 rxjs
库(5.5 之前的版本)。如果你更新它,你将不得不使用管道运算符:
import {map} from 'rxjs/operators';
...
people: Personal[];
...
ngOnInit() {
// Let's get rid of lodash for the mapping thing
this.http.get<Map<string, Personal>>('/people/get')
.pipe(map(data => Object.keys(data).map(key => data[key])))
.subscribe((people: Personal[]) => this.people = people);
}
作为附加观察,因为您正在使用 lodash 函数将对象转换为数组。显然 this.http.get<Personal[]>
并没有真正返回 Personal
的数组,而是一个对象,因此您可能必须编写 get
像这样的方法(就像我在上面的代码中所做的那样):
this.http.get<{[id: string]: Personal}>
或
this.http.get<Map<string, Personal>>
关于angular - 如何从 Angular 中的 Observable 中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61720971/