2016-07-26 24 views
0

我有一個工廠,做一個http調用,並在錯誤回調我想設置一個屬性值,例如this.password = nullthis.password不指向密碼。在AngularJS中如何修改從服務內部的回調服務屬性

在另一方面,當我做POST數據發送罰款:password: this.password

密碼財產的範圍應該是不同的吧?或者我錯過了別的東西?

.factory('LogInService', function($http) { 

    return { 
    username: null, 
    password: null, 
    logIn: function() { 
     return $http({ 
     method: 'POST', 
     url: 'http://my-domain/api/signin', 
     data: { 
      username: this.username, 
      password: this.password 
     } 
     }) 
     .then(
     function(success){ 

     }, 
     function(err){ 
      // reset password field 
      this.password = null; // <-- not working 
     } 
    ); 
    } 
    } 
}); 

我可以將所有屬性和方法設置爲一個var然後返回它,但我寧願上面的方法。我的意思是:

var myService = { 
    // my property and methods... 
} 

errorCallBack = function(){ 
    myService.password = null; 
} 

return myService; 

回答

2

你有一個範圍界定問題。應該很容易做到這一點。一如既往,未經測試,但似乎會奏效。

.factory('LogInService', function($http) { 

    return { 
    username: null, 
    password: null, 
    logIn: function() { 
     var svc = this; //<---- 
     return $http({ 
     method: 'POST', 
     url: 'http://my-domain/api/signin', 
     data: { 
      username: svc.username, //<--- 
      password: svc.password //<--- 
     } 
     }) 
     .then(
     function(success){ 

     }, 
     function(err){ 
      // reset password field 
      svc.password = null; //<---- 
     } 
    ); 
    } 
    } 
}); 
+0

我正在嘗試'var _this = this;'但在'return'之前,在'logIn'函數內工作。合理。謝謝 – Mikel

1

您需要learn about this

您可以使用arrow functions修復您的問題,但不會更改this的含義。

您可能想要use Babel將您的ES6代碼編譯爲ES5,以便瀏覽器在您現代的代碼庫中表現良好。

+0

是否在野外廣泛支持箭頭功能? – CollinD

+0

查看此兼容性表:https://kangax.github.io/compat-table/es6/。您可以使用Babel或類似工具將箭頭函數和其他現代語法編譯爲所有瀏覽器都能理解的內容。 – bevacqua

+0

我會看看 – Mikel