JustHeadache
JustHeadache

Reputation: 39

Why is this Array undefined and how to fix?

I have a problem with my Code. It says that my Array is undefined but a method later it works fine. Here's the code:

books: IBook[] = [];
[...]
  ngOnInit() {
    this.service.getEmployees().subscribe(
      (listBooks) => this.books = listBooks,
      (err) => console.log(err)
    ); 
  }
[...]
 events: CalendarEvent[] = [
    {
      start: new Date(),
      end: new Date(),
      title: ""+this.books[0].device, //this.books[0] is undefined
      color: colors.yellow,
      actions: this.actions,
      resizable: {
        beforeStart: true,
        afterEnd: true
      },
      draggable: true
    },
[...]
test(){                     //this method is linked to a button
  console.log(this.books[0]) //after clicking it works fine
}
[...]

The Test method is after the array, where it says it's 'undefined' so it cant be undefined can it?

Upvotes: 0

Views: 96

Answers (2)

Antonis
Antonis

Reputation: 557

First of all the getEmployees() running in the ngOnInit is async. The browser continues executing events assignment synchronously but the listBooks will be resolved from the call at some point later.

Therefore you should fix you logic and initialize events after your data are resolved and maybe handle that information you're expecting in case it's undefined:

title: this.books[0] ? ""+this.books[0].device : ""

Lastly, you need an immutable operation on the books when you want to assign the new data:

this.books  = [...listBooks]

Upvotes: 0

Ichraf
Ichraf

Reputation: 355

Where are you doing this in your code ? :

 events: CalendarEvent[] = [
    {
      start: new Date(),
      end: new Date(),
      title: ""+this.books[0].device, //this.books[0] is undefined
      color: colors.yellow,
      actions: this.actions,
      resizable: {
        beforeStart: true,
        afterEnd: true
      },
      draggable: true
    },
[...]

If this code is in the ngOnInit method, you should put it in the subscribe callback like this:

 ngOnInit() {
    this.service.getEmployees().subscribe(
      (listBooks) => {
         this.books = listBooks
         [...]
         events: CalendarEvent[] = [
        {
          start: new Date(),
          end: new Date(),
          title: ""+this.books[0].device, //this.books[0] is undefined
          color: colors.yellow,
          actions: this.actions,
          resizable: {
          beforeStart: true,
          afterEnd: true
         },
         draggable: true
        },
        [...]
      },
      (err) => console.log(err)
    ); 
  }

The call of getEmployees is asynchronous which means that the events object may be initialized before the callback function where the books object gets initialized. Hope it is clear

Upvotes: 2

Related Questions