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

2024-04-29

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 中有一些错误,重点是如何从成功回调内部访问服务范围?

EDIT:虽然这个问题的答案是正确的,但我转向了factory乔什和马克都推荐的方法


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

.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在这些情况下。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AngularJS 服务 http 成功函数使用错误的“this”范围 的相关文章

随机推荐