gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:07:21 27 4
gpt4 key购买 nike

$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 都推荐了它

最佳答案

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

.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

关于http - AngularJS 服务 http 成功函数使用错误的 "this"范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14904830/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com