2016-05-04 14 views
0

問題は、私はsetメソッドにアクセスするためにできないことです。

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' 

      }); 
     } 
    } 
} 

私はthis.set()

おかげにアクセスするためのソリューションを検索します!

+2

はなぜポストの前に変数右に「この」を代入しようとしないで、その後、コールバックでその変数を使用します。 – ronster37

答えて

3

thisのコピーをコールバックの外側に保存して使用します。 ES6を使用して

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

    }; 
} 

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

    }; 
} 
+0

本当にありがとう! –

関連する問題