I want to return a value from Rethinkdb using Horizon:
ionViewLoaded() {
let exampleValue;
exampleValue = this.getValue();
console.log(exampleValue); // gives me "undefined"
}
getValue() {
let hz = new Horizon({host: "localhost:3100"});
hz.connect();
let table = hz('values');
table.find(1).fetch().subscribe((val) => {
return val;
});
}
I need this value outside function and then I want to write simple if/else statement (if I do this into query then I get weird error - view is reloading over 200 times...). Is there anyway to return this value?
You should make a service out of this whenever you are retrieving something from the database or an api. It's what it is made for.
Moving on with your question, the exampleValue
is undefined in this case because getValue
does not wait for the subscription to fire in table.find(1).fetch()
thus returning an undefined.
What you can do is, return the observable and subscribe into it in your ionViewLoaded
or make a Promise
in getValue
.
I'll just demonstrate option #1.
ionViewLoaded() {
this.getValue().subscribe((exampleValue) => {
console.log(exampleValue);
});
}
getValue() {
let hz = new Horizon({host: "localhost:3100"});
hz.connect();
let table = hz('values');
return table.find(1).fetch();
}