如何将 Observable<any> 转换为 array\[\]

新手上路,请多包涵

我在打字稿中有以下方法,我需要绑定到角度网格

国家服务

GetCountries()  {
  return this.http.get(`http://services.groupkt.com/country/get/all`)
    .map((res:Response) => <CountryData[]>res.json().RestResponse["result"]);
}

网格组件

  template: `
        <ag-grid-ng2 style="width: 100%" #agGrid class="ag-material"
                    rowHeight="50"
                    [gridOptions]="myGridOptions"
                     >
            </ag-grid-ng2>
        `,

  this.myGridOptions.rowData= this.CountryService.GetCountries();

国家数据

export class CountryData{
  name: string;
  alpha2_code: string;
  alpha3_code: string;
}

但是 GetCoutries 将返回任何无法绑定到 rowData 的 Observable?

如何在 typescript 中将 Observable 转换为 CountryData[]?

您可以在这里找到 JSON 数据: http ://services.groupkt.com/country/get/all

原文由 Ragavan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 700
2 个回答

你需要订阅你的 observables:

 this.CountryService.GetCountries()
    .subscribe(countries => {
        this.myGridOptions.rowData = countries as CountryData[]
    })

而且,在您的 html 中,只要需要,您可以将 async 管道传递给它。

原文由 CozyAzure 发布,翻译遵循 CC BY-SA 3.0 许可协议

在 Angular 4.3+ 中使用 HttpClient(Http 的替代品),整个映射/转换过程变得更简单/消除了。

使用 CountryData 类,您将定义如下服务方法:

 getCountries()  {
  return this.httpClient.get<CountryData[]>('http://theUrl.com/all');
}

然后当你需要它时,定义一个这样的数组:

 countries:CountryData[] = [];

并像这样订阅它:

 this.countryService.getCountries().subscribe(countries => this.countries = countries);

此处还发布了 完整的设置答案。

原文由 mohsenmadi 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进