AngularJS服务http成功功能使用错误的“这个”范围
发布时间:2020-12-17 07:43:05 所属栏目:安全 来源:网络整理
导读:$http.put的成功函数无法访问正在调用的服务范围.我需要在PUT请求的回调中更新服务的属性. 这是我正试图在服务中做的一个例子: var myApp = angular.module('myApp',function($routeProvider) {// route provider stuff}).service('CatalogueService',funct
$http.put的成功函数无法访问正在调用的服务范围.我需要在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,config) { alert(data); }); } } 对不起,如果在JS中有一些错误,主要是如何从成功回调内部访问服务范围? 编辑:虽然这个问题的答案是正确的,但我切换到工厂方法,Josh和Mark建议
在分配给它的变量(通常称为)上创建一个闭包,以便您的回调函数可以访问您的服务对象:
app.service('CatalogueService',$http) { var that = this; ... ).success(function(data,config) { that.items.push(data); 这是一个Plunker,使用$timeout而不是$http来演示. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |