Reputation: 4634
I want to return result directly (Normally we try to put to data and access that data yeah. but now how I want is directly). Like when we call hello()
function I want to return result
variable.
I try like the following, but it doesn't return yeah. How do I try?
hello: function() {
var result = "";
this.$http.get(window.location.href).success(function(data) {
result = data;
}).error(function (data, status, request) {
});
return result;
}
Upvotes: 0
Views: 1411
Reputation: 7225
Looks like it doesn't return the data because the request is async. Your method sets up the request and then returns immediately, synchronously, before the request had a chance to assign any data to the result
variable.
You can try to change your code slightly:
hello: function() {
var result = {};
this.$http.get(window.location.href).success(function(data) {
result.data = data;
result.ready = true;
}).error(function (data, status, request) {
});
return result;
}
That should enable you to access the data elsewhere (as result.data
), but only after the async query has succeeded. The result.ready
flag would tell you if and when that has happened.
In my opinion, it would definitely be better to work with promises, though, e.g. using jQuery Deferreds and promises, or ES6 promises along with a polyfill.
Upvotes: 2