Mike
Mike

Reputation: 71

Ionic3: Cannot access class property from inside events.subscribe

I have a class that is listening for an event. When that event happens, I want to push the data coming with the even to the array and display it. This is my class:

export class randomClass {

  someArray:Array<string>;

  constructor(public navCtrl: NavController, 
              public navParams: NavParams,
              public events: Events) {

    events.subscribe('event',
      (data) => {
        //some random code
        this.someArray.push(data); //this fails
      }
    )
  }

The error that I get is: TypeError: undefined is not an object (evaluating '_this.communication.push')

I'm guess this is trivial but can't find the answer anywhere.

Upvotes: 1

Views: 105

Answers (3)

Ajantha Bandara
Ajantha Bandara

Reputation: 1551

The problem is when transpile this code into javascript, the value of the variable someArray is equal to undefined. That how transpiler works. You cannot push data into an undefined variable. Because it is not an array. If you initialize it as someArray:Array<string> = [] it will be transpile into a var someArray = []. Now you can push the data into the array.

Upvotes: 0

sebaferreras
sebaferreras

Reputation: 44669

The problem was that I had to initialize the property with an empty array (can somebody explain why?)

When you do this

someArray: Array<string>;

You're just declaring a property called someArray and setting its type to be an Array of strings, but you're not initializing that property, so initially someArray will be undefined.

So when you try to do this:

this.someArray.push(data);

since this.someArray is undefined, you're trying to call the push method of undefined, which does not exist (and that's why the error says something like TypeError: undefined is not an object).

Just like you've said, the solution is to initialize someArray with an empty Array. That way, you will be able to call the push method since it's defined in every object whose type is an Array.

someArray: Array<string> = [];

Upvotes: 1

Mike
Mike

Reputation: 71

Ok. The problem was that I had to initialize the property with an empty array (can somebody explain why?). The following solved the problem.

communication:Array<string> = [];

Upvotes: 1

Related Questions