如何转换Observable 到数组[]

问题描述 投票:21回答:4

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

CountryService

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

GridComponent

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

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

CountryData

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

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

如何在打字稿中将Observable转换为CountryData []?

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

angular typescript rxjs
4个回答
22
投票

您需要订阅您的可观察量:

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

并且,在您的HTML中,无论何时需要,您都可以将async管道传递给它。


12
投票

在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);

一个完整的设置答案is posted here也。


2
投票

这应该工作:

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

为此,您需要导入以下内容:

import 'rxjs/add/operator/map'

0
投票

//零件。 home.ts:

  contacts:IContacts[];


ionViewDidLoad() {
this.rest.getContacts()
.subscribe( res=> this.contacts= res as IContacts[]) ;

// reorderArray。只接受数组

    Reorder(indexes){
  reorderArray(this.contacts, indexes)
}

//服务res.ts

getContacts(): Observable<IContacts[]> {
return this.http.get<IContacts[]>(this.apiUrl+"?results=5")

它工作正常

© www.soinside.com 2019 - 2024. All rights reserved.