AngularJS服务http成功函数使用错误的"this"范围

Pet*_*ete 14 service http angularjs

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);
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

对不起,如果JS中有一些错误,重点是如何从成功回调中访问服务范围?

编辑:虽然这个问题的答案是正确的,但我转向了factory方法,因为Josh和Mark都推荐了它

Jos*_*ler 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
  };
};
Run Code Online (Sandbox Code Playgroud)

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


Mar*_*cok 16

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

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

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

  • 在这种情况下,我仍然更喜欢工厂方法,但实际上回答问题的+1.:-) (4认同)