B.T
B.T

Reputation: 29

how to reach element of json array

I am using new Date function for countdown timer and ı want to load dates from json

my code like this.

home.ts

export class HomePage     {
 public products: any;
 private eventDate: Date = new Date('July 20, 2019 03:24:00');

constructor(public navCtrl: NavController ,    public navParams: NavParams,
    public myService : MyServiceProvider,public http: Http,) {

      this.loadProducts();

}

this.eventDate=new Date(this.products[0].start_time);

loadProducts(){
  this.myService.load()
  .then(data => {
    console.log(data);
    this.products= data;

});
}

and I am experiencing this error

Uncaught (in promise): TypeError: Cannot read property '0' of undefined TypeError: Cannot read property '0' of undefined

Upvotes: 0

Views: 78

Answers (2)

Shohel
Shohel

Reputation: 3934

The following code should work to your application. Check has there any data to products array.

export class HomePage {
  public products: any;
  private eventDate: Date = new Date('July 20, 2019 03:24:00');

  constructor(public navCtrl: NavController
    , public navParams: NavParams
    , public myService: MyServiceProvider
    , public http: Http) {
    this.loadProducts();
  }  

loadProducts(){
  this.myService.load()
    .then(data => {
      console.log(data);
      this.products = data;

      if(this.products.length > 0) {
        this.eventDate = new Date(this.products[0].start_time);
      }
    });
}

Upvotes: 0

Piyush Jain
Piyush Jain

Reputation: 1986

Set this value this.eventDate=new Date(this.products[0].start_time); inside .then of loadProducts() method.

Upvotes: 1

Related Questions