Restangular inside factory
I have try to use Restangualar inside factory. But it given the "Error: this is undefined". But working properly in $http.get(). Is it possible to use 'this.variable' inside Restangular ? simple eg:
- Using http.get (print 1)
.factory('Accounts', function ($http) {
var getAccounts = function () {
this.abc = 1;
};
getAccounts.prototype.accts= function () {
var url = "https://localhost:8080/accounts";
$http.get(url).success(function (data) {
console.log(this.abc);
//this.abc = data;
}.bind(this));
};
return getAccounts;
}) ;
- Using Restangular ("Error: this is undefined".)
.factory('Accounts', function (Restangular) {
var getAccounts = function () {
this.abc = 1;
};
getAccounts.prototype.accts= function () {
var url = "accounts";
Restangular.all(url).getList().then(function (data) {
console.log(this.abc);
//this.abc = data;
});
};
return getAccounts;
});
Hey,
As you can see using $http you're actually manually binding this to the function.
In this case as it says there's no this, as this is the function for this promise.
In order to use this, you should do something like:
Restangular.all(url).getList().then(_.bind(function (data) {
console.log(this.abc);
//this.abc = data;
}, this));
That way, the callback function has this binded to the object that's in that context.
Let me know if that works out for you!
Anyway, I'm giving you this _.bind example as this is what I know. I don't know what that function() {}.bind(this) you're showing does as I've never seen that before.
Please let me know if this fixes your problem
Hi mgonto,
yes.It work perfectly. Thanks a lot for your great solution. }.bind(this) used function prototype bind.