2016-05-04 22 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以外的回調並使用它。

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

    }; 
} 

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

    }; 
} 
+0

非常感謝你! –