I'm struggling with an error. It tooks me over 2 days and still no solution... I'm using Ionic2 as a frontend and Horizon with RethinkDB as a backend. I have a table called 'messages' and few messages in it. I just want to get all these messages and show them on my HomePage. Here is my code:
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
declare var Horizon;
@Component({
templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
test: any[];
constructor(public navCtrl: NavController) {
}
getMessages(){
let test = [];
let hz = new Horizon({host: 'localhost:3100'});
hz.connect();
let messages = hz('messages');
messages.watch().subscribe(messages => {
for(let i = 0; i<messages.length; i++){
console.log(messages[i].text);
console.log(messages[i].id);
this.test.push([{
text: messages[i].text,
id: messages[i].id
}])
}
});
}
}
I tried with many combinations of this.test.push but still no luck. I'm doing something wrong... Hope you guys help me!
The answer to this problem was just ensuring to reference the variable you think you're referencing.
this.test
is undefined. Instead of let test = [];
you should change it to this.test = [];
.
Or you can change this.test.push(...
to test.push(...
and it should also work fine.
Being cautious when using this
and juggling scope in Javascript is one of the trickiest parts of the language. I wish there was some indicator in the error as to what part in the chain is actually undefined
as you thought .push
was undefined
on this.test
where actually it was test
which was undefined on the this
object.