shadowfs
shadowfs

Reputation: 33

push a property into array ionic

i have an API looking like this: my API

the problem is that when i want to use the API for data binding i get the error that says data binding is only possible for array. not objects. what i need from my API is only cities. what i figured out is that maybe its because the json file is a nested object and cant be converted into array. so i want to see if there is a way to just extract the cities and put it into an array to use for binding. to be clear here i post my codes: the StatesProvider for getting the API:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
@Injectable()
export class StatesProvider {
constructor(public http: HttpClient, public platform: Platform) {}
getCities() {
  return new Promise(resolve => {
  this.http.get("https://***"+lang+"/state/1").subscribe(data => {
    resolve(data);
  }, err => {
    console.log(err);
  });
 });
}}

my state.ts component:

import { Component, ViewChild } from '@angular/core';
import { NavController, App, ViewController, Slides } from 'ionic-angular';
import { StatesProvider } from '../../providers/states/states';
@Component({
  selector: 'page-state',
  templateUrl: 'sell.html'
})
export class StatePage {
  @ViewChild('mySlider') slider: Slides;
  cities: any;
  constructor(public viewCtrl: ViewController, public appCtrl: App,
    public navCtrl: NavController, public stateProvide: StatesProvider) {
    this.getCities();
  }
  getCities() {
    this.stateProvide.getCities()
      .then(data => {
        this.cities = data;
        console.log(this.cities);
      });
  }

finally the html file, the part that i have problem with looks like sth like that:

<ion-content padding>
  <ion-slides #mySlider (ionDidChange)="onSlideChanged($event)">
    <ion-slide *ngFor="let city of cities.cities">
      <ion-list>
        <ion-item>
          <ion-thumbnail item-left>
            <img [src]="city.image_thumb">
          </ion-thumbnail>
          <h2 text-end>{{city.name}}</h2>
        </ion-item>
      </ion-list>
    </ion-slide>
   </ion-slides>
 </ion-content>

now thats for when i read somewhere that for APIs like this you could use *ngFor like this one that i've writed: *ngFor="let city of cities.cities". but still i get the error that says: Cannot read property 'cities' of undefined

Upvotes: 0

Views: 381

Answers (1)

Pardeep Jain
Pardeep Jain

Reputation: 86800

Your code seems fine, Try using safe navigation ? like this -

<ion-slide *ngFor="let city of cities?.cities">

Upvotes: 1

Related Questions