How do I declare a arrray in Ionic and use?

Asked

Viewed 47 times

0

export class StarterorderPage implements OnInit {
  $orders: [
    { id: number, description: string }
  ];
  constructor( public http: HttpClient, private route: ActivatedRoute) { }

  ngOnInit() {
  }

  MyFunction() {
    this.$orders[0].id = 230;
    this.$orders[0].description = 'descricao numero duzentos e trinta ';
    console.log('Observe->', this.$orders[0].id, this.$orders[0].description);
  }

ERROR Typeerror: Cannot read Property '0' of Undefined At Starterorderpage.push.. /src/app/starterorder/starterorder.page.ts.StarterorderPage.Apistarterorder (starterorder.page.ts:24) At object.Eval [as handleEvent] (Starterorderpage.html:24) handleEvent (core.js:23107) at callWithDebugContext (core.js:24177) At object.debugHandleEvent [as handleEvent] (core.js:23904) dispatchEvent (core.js:20556) at core.js:21003 At Htmlbuttonelement. (Platform-browser.js:993) At Zonedelegate.push.. /node_modules/zone.js/dist/zone.js.Zonedelegate.invokeTask (zone.js:423) At Object.onInvokeTask (core.js:17290)

This code is not working!!! How I can declare and add values and then use them?

  • 1

    Your problem is not with Ionic or TS but with JS

  • You know how I fix it? In theory, I just need to fill the Orders array correctly and then move on to a webservice call...!

  • 1

    tries $Orders.push({230,'Description number two hundred and thirty '});

  • 1

    Read here how to use arrays in JS : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

  • 1

    Which version of Ionic are you using? That’s not you helping?

  • I’ve read it all! I understand...I’m using version 4 of Ionic. Thank you!

Show 1 more comment

1 answer

1


To add elements to an array, do so:

MyFunction() {
    this.$orders.push({id: 230, description: 'descricao numero duzentos e trinta '});
    console.log('Observe->', this.$orders[0].id, this.$orders[0].description);
}

I always like to start an even empty array. This avoids many problems:

    $orders: { id: number, description: string }[] = [];
  • 1

    Straight! Problem solved! Thank you so much for the whim and your time! Thank you all!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.