14

a 的成功函数$http.put无权访问this它在内部被调用的服务范围。我需要在 PUT 请求的回调中更新服务的属性。

这是我在服务中尝试做的一个简化示例:

var myApp = angular.module('myApp', function($routeProvider) {
// route provider stuff
}).service('CatalogueService', function($rootScope, $http) {
    // create an array as part of my catalogue
    this.items = [];

    // make a call to get some data for the catalogue
    this.add = function(id) {
        $http.put(
            $rootScope.apiURL,
            {id:id}
        ).success(function(data,status,headers,config) {
             // on success push the data to the catalogue
             // when I try to access "this" - it treats it as the window
             this.items.push(data);
        }).success(function(data,status,headers,config) {
            alert(data);
        });
    }
}

对不起,如果JS中有一些错误,主要是我如何从成功回调内部访问服务范围?

编辑:虽然这个问题的答案是正确的,但我改用factory了 Josh 和 Mark 推荐的方法

4

2 回答 2

23

据我所知,你不能。但无论如何我都不会尝试以这种方式运行服务。这是一种更清洁的方法:

.factory('CatalogueService', function($rootScope, $http) {
  // We first define a private API for our service.

  // Private vars.
  var items = [];

  // Private methods.
  function add( id ) {
    $http.put( $rootScope.apiURL, {id:id} )
    .success(function(data,status,headers,config) { items.push(data); })
    .then(function(response) { console.log(response.data); });
  }

  function store( obj ) {
    // do stuff
  }

  function remove( obj ) {
    // do stuff
  }

  // We now return a public API for our service.
  return {
    add: add,
    store: store,
    rm: remove
  };
};

这是在 AngularJS 中开发服务的一种非常常见this的模式,在这些情况下不需要任何使用。

于 2013-02-15T23:08:43.367 回答
16

that在分配给的变量(通常称为 )上创建一个闭包,this以便您的回调函数可以访问您的服务对象:

app.service('CatalogueService', function($rootScope, $http) {
    var that = this;
    ...
        ).success(function(data,status,headers,config) {
          that.items.push(data);

这是一个使用 $timeout 而不是 $http 的Plunker来演示。

于 2013-02-16T18:32:58.697 回答