Reputation:
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
Reputation: 40564
You have two issues here:
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.
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
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
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