AngularJS服务http成功函数使用了错误的"this"作用域
AngularJS服务http成功函数使用了错误的"this"作用域
$http.put
的success函数不能访问其被调用服务的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中存在某些错误,我表示抱歉,重要的是如何从success回调中访问服务作用域。
编辑:虽然这个问题的答案是正确的,但我已经转换到了factory
方法,因为Josh和Mark都建议这样做。
admin 更改状态以发布 2023年5月21日
创建一个闭包,覆盖一个变量(通常称为that
),该变量被赋值为this
,以便您的回调函数可以访问您的服务对象:
app.service('CatalogueService', function($rootScope, $http) { var that = this; ... ).success(function(data,status,headers,config) { that.items.push(data);
。这里是一个Plunker,它使用$timeout而不是$http来进行演示。
据我所知,你无法这样做。但我也不会尝试那种方法来运行服务。以下是一个更简洁的方法:\n
.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 }; };
\n这是使用AngularJS开发服务的非常常见的模式,而在这些情况下不需要使用this
。