restangular icon indicating copy to clipboard operation
restangular copied to clipboard

Restangular inside factory

Open sarath2 opened this issue 13 years ago • 3 comments

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:

  1. 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;
}) ;
  1. 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;
 });

sarath2 avatar Aug 23 '13 03:08 sarath2

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!

mgonto avatar Aug 23 '13 18:08 mgonto

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

mgonto avatar Aug 23 '13 18:08 mgonto

Hi mgonto,

yes.It work perfectly. Thanks a lot for your great solution. }.bind(this) used function prototype bind.

sarath2 avatar Aug 23 '13 19:08 sarath2