I want to retrieve an object that stored in parse platform and I'm using ionic framework. so I wrote this code in Home.ts :
export class HomePage {
result: string = 'sample' ;
constructor(public navCtrl: NavController) {
Parse.serverURL = 'https://parseapi.back4app.com/';
Parse.initialize("MY_APP_ID", "MY_JS_KEY");
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("wN9bVUA9Hu", {
success: function(gameScore) {
// The object was retrieved successfully.
this.result = gameScore.get("score").toString();
console.log(this.result);
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
}
}
and object's id is = wN9bVUA9Hu, so that should retrieve the object's score which is 9. but as you see here : result
result didn't change in Home.html but in the console, it is 9.
here is my Home.html code :
<ion-header>
<ion-navbar>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h4>{{result}}</h4>
</ion-content>
how can I solve this and show the retrieved object in Home.html ?
thanks.
I'm sorry, this should have been obvious to me but my eyes just slip over these things.
var func1 = () => console.log(this.result);
var func2 = function { console.log(this.result); }
These two statements are not the same. Where possible, your sanity will be improved if you use arrow functions (e.g. func1
). They are newer to JavaScript so many examples you see will not include them.
In an arrow function this
points to same object inside the function as it does outside. With the function
syntax this
is reassigned to something else depending on how it was called. So in your code, when you say this.result = gameScore.get("score").toString();
the problem is that this
is not referencing the instance of HomePage
.
If you need to keep the function
syntax (a few libraries rely on reassignment of this
) then you have to do something like...
const self = this;
query.get("wN9bVUA9Hu", {
success: function(gameScore) {
self.result = gameScore.get("score").toString();
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
}