2015-11-29 193 views
1

分配值我有一個服務:角服務不空對象

storeApp.service('currentCustomer',function($http) { 
    this.customerID = 0; 
    this.customerInfo = {} 
    this.customerAttributes = {} 
    this.getCustomerInfo = function() { 
     if (this.customerID != 0) { 
      $http.get('/customers/' + this.customerID). 
      then(function (result) { 
       this.customerInfo = result.data[0] 
      }) 
     } 
    } 

和控制器:

storeApp.controller('storeList',function($scope,$http,currentCustomer) { 
    $scope.changeCust = function changeCust(id) { 
     currentCustomer.customerID = id; 
     currentCustomer.getCustomerInfo() 
     console.log("After Change customer:") 
     console.log(currentCustomer) 
    } 
    $scope.selectedStore = currentCustomer 
}); 

如果我嘗試訪問selectedStore.customerID,我得到的值。

如果我嘗試訪問selectedStore.customerInfo,我得到一個空數組,即使當我把控制檯登錄到檢查值時,它說它們被分配。

任何想法我做錯了什麼?感謝大家。

回答

1

您手動分配一個值CustomerId,和你的服務的方法是customerInfo分配一個值。服務方法中除this外,與服務中的this不一樣。您應該在服務中實例化一個var self = this;引用,並在所有對象操作中使用此值。例如:self.customerInfo = ....

+0

謝謝。那麼'this'指的是方法本身呢?我很感激幫助。 – user3166537

+1

是的,確切地說。我認爲這篇文章在解釋JavaScript中的上下文方面做得很好:http://ryanmorr.com/understanding-scope-and-context-in-javascript/ – mrtig

1

您對this的參考號已在功能內更改。第一家店在某些變量this引用,然後分配屬性,有些人更喜歡用這個詞self但我更喜歡service

storeApp.service('currentCustomer',function($http) { 
    var service = this; 
    service.customerID = 0; 
    service.customerInfo = {} 
    service.customerAttributes = {} 
    service.getCustomerInfo = function() { 
     if (service.customerID != 0) { 
      $http.get('/customers/' + this.customerID). 
      then(function (result) { 
       service.customerInfo = result.data[0] 
      }); 
    } 
}