angular - 如何从 Angular 中的 Observable 中提取数据

标签 angular typescript rest

我有一个基于 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/

相关文章:

java - 如何修复 org.codehaus.jackson.map.exc.UnrecognizedPropertyException

Angular 7 Bootstrap 指令不加载

angular - 在 angular2 中找不到名称错误

angular - 我们可以同时使用 Angular Material 和 Bootstrap 来进行 Angular 项目吗?

javascript - 如何使用 TypeScript 将单独文件中的两个类合并到一个 ES6 模块中?

javascript - 如何通过 Typescript 中的迭代处理数组字符串

node.js - 如何在 typescript 中编写 Sequelize 交易

java - 如何在 REST Web 服务中接收大型 XML 文件

javascript - 在拦截器angular2中实现http请求

php - PayPal REST API 更新计费协议(protocol)