user8590996
user8590996

Reputation:

Update array from event callback

I have to update an array (which is bounded in my html template) from an event based call back function. But it is undefined when I access it inside the callback.

export class HomePage {

  constructor(public navCtrl: NavController) {
    let consumer: string[]; // <=== Updating this array
    const realtime = new Ably.Realtime('API-KEY');
    const channel = realtime.channels.get("test");
    channel.subscribe((msg) => {

      console.log("Received: " + msg.data);
      consumer.push(msg.data); // <=== but "consumer is undefined here"

    });
  }

}

HTML TEMPLATE

  <div>
    <ul *ngFor="let item of consumer">
      <li>{{item}}</li>
    </ul>
  </div>

Upvotes: 2

Views: 174

Answers (3)

Saravana
Saravana

Reputation: 40564

You have two issues here:

  1. consumer is not exposed by the component. It is available only inside the constructor. So you won't be able to loop though it in the template. Change it to a property.

  2. consumer is never initialized. You have only given its type, but not assigned anything to it.

You can fix these by declaring and initializing consumer as a property:

export class HomePage {
  consumer: string[] = []; // Declare and initialize here
  constructor(public navCtrl: NavController) {
    const realtime = new Ably.Realtime('API-KEY');
    const channel = realtime.channels.get("test");
    channel.subscribe((msg) => {

      console.log("Received: " + msg.data);
      this.consumer.push(msg.data);

    });
  }

}

Upvotes: 1

Carsten
Carsten

Reputation: 4208

Move let consumer: string[]; // <=== Updating this array outside of the constructor -> above it for example.

Then, remove the 'let' keyword and initialize it to an empty array = []; Now you can use it in a template.

Upvotes: 1

alfredson
alfredson

Reputation: 241

You are not initializing your consumer array.

Change this line

let consumer: string[];

to

let consumer: string[] = [];

then it is an empty array and you can push some data in it.

Regards

Upvotes: 1

Related Questions