How to convert Observable to array[]

后端 未结 4 1771
暗喜
暗喜 2020-12-05 04:13

I have following method in typescript, I need to bind to angular grid

CountryService

GetCountries()  {
  return this.http.get(`http         


        
相关标签:
4条回答
  • 2020-12-05 04:50

    //Component. home.ts :

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

    // reorderArray. accepts only Arrays

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

    // Service . res.ts

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

    And it works fine

    0 讨论(0)
  • 2020-12-05 04:56

    Using HttpClient (Http's replacement) in Angular 4.3+, the entire mapping/casting process is made simpler/eliminated.

    Using your CountryData class, you would define a service method like this:

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

    Then when you need it, define an array like this:

    countries:CountryData[] = [];
    

    and subscribe to it like this:

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

    A complete setup answer is posted here also.

    0 讨论(0)
  • 2020-12-05 04:59

    This should work:

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

    For this to work you will need to import the following:

    import 'rxjs/add/operator/map'
    
    0 讨论(0)
  • 2020-12-05 05:04

    You will need to subscribe to your observables:

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

    And, in your html, wherever needed, you can pass the async pipe to it.

    0 讨论(0)
提交回复
热议问题