2016-10-17 51 views
0

我作爲節目此代碼工作正常服務功能如下使用服務可以獲取和設置變量

.service('ItemService', ['$http', function ($http) { 
    var items = [{'item_id': '1', 'item_name': 'abc'}]; 
     return { 
      getItems: function() { 
       return items; 
       }, 
      setItems: function (value) { 
       items = value; 
      } 
    }; 
}]); 

,我想使項目動態,例如

var items = $http({ 
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
    method: 'POST', 
    url: 'http://localhost/app/item/get/10', 
}).then(function (response) { 
    return response.data; 
}); 

我該怎麼做?

回答

1

您服務將是這樣

.service('ItemService', ['$http', function($http) { 

    return { 
     getItems: function(id) { 
      return $http({ 
       headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, 
       method: 'GET', 
       url: 'http://localhost/app/item/get/' + id, 
      }) 
     }, 
     setItems: function(items) { 
      return $http({ 
       headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, 
       method: 'POST', 
       url: 'http://localhost/app/item/' + items, 
      }) 
     } 
    }; 
}]); 

你應該把它裏面你控制器這樣

ItemService.getItems().then(function(response){ 
    //Retrieve the data 
    $scope.items = response.items; 
}, function(error){ 
    //Handle the errors 
}) 
+0

我希望我的服務正是這樣 – Nakul

+0

但我想更換項目只有 – Nakul

+0

我不明白 – Weedoze

0
.service('ItemService', ['$http', function ($http) { 
    // I want to initialize this items array before I call getItems funtion, Anyway to do the same? 
    var items = [{'item_id': '1', 'item_name': 'abc'}]; 

     //Below section I want exactly same I will change items array from my controller and also I will use getItem again to get this items array agian. My getItems should only return the items array 
     return { 
     getItems: function() { 
      return items; 
      }, 
     setItems: function (value) { 
      items = value; 
    } 
}; 
}]);