0

The problem is that i can't to access to set method :

  this.$get = function( $http ) {

    return 
    {
      set: function(UserData)
      {
        this.user = UserData ;
        localStorage.setItem('user', JSON.stringify( UserData ) );
      },

      get: function()
      {
        return this.user;
      },

      send: function(data)
      {
        $http.post(BASE_URL + 'user/login', data)
            .then( function( res ){

              // Error !

              this.set(res.data); 

              console.log(this); // return window object

              // Here i want to access to 'this.set()'
              // but i get error: 'ypeError: this.set is not a function'

            });
      }
    }
 }

I search for solution to access to this.set()

Thanks !

Moti Winkler
  • 308
  • 1
  • 4
  • 19
  • 2
    why don't try assigning 'this' to a variable right before the post, and then use that variable in the callback. – ronster37 May 04 '16 at 17:16

1 Answers1

3

Save a copy of this outside of the callback and use that.

this.$get = function ($http) {
  return {

    set: function (UserData) {
      this.user = UserData;
      localStorage.setItem('user', JSON.stringify(UserData));
    },

    get: function () {
      return this.user;
    },

    send: function (data) {
      var _this = this;
      var url = BASE_URL + 'user/login';
      $http.post(url, data).then(function (res) {
        _this.set(res.data); 
      });
    }

  };
}

Using ES6:

this.$get = function ($http) {
  return {

    set(UserData) {
      this.user = UserData;
      localStorage.setItem('user', JSON.stringify(UserData));
    },

    get() {
      return this.user;
    },

    send(data) {
      let url = BASE_URL + 'user/login';
      $http.post(url, data).then(res => {
        this.set(res.data); 
      });
    }

  };
}
Ilia Choly
  • 18,070
  • 14
  • 92
  • 160