使用错误的&QUOT

使用错误的&QUOT

本文介绍了使用错误的&QUOT AngularJS服务HTTP成功函数;此"范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

的成功,函数 $ http.put 没有访问服务这个范围它被称为内。我需要在呼叫从PUT请求重新更新服务的属性。

The success function of a $http.put doesn't have access to the this scope of the service it's being called inside. I need to update a property of the service in the call back from the PUT request.

这是我想要的服务做了削减例如:

This is a cut down example of what I'm trying to do in a service:

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的一些错误,主要的问题是如何从成功回调内部访问的服务范围?

Sorry if there are some errors in the JS, the main point is how do I access the service scope from inside the success callback?

修改:在这个问题的答案是正确的,我切换到工厂方法,既约什和马克推荐它。

EDIT : while the answer to this question was correct, I switched to the factory method as both Josh and Mark recommended it

推荐答案

在分配给是)创建一个封闭>这个让你的回调函数将有机会获得你的服务对象:

Create a closure over a variable (often called that) that is assigned to this so that your callback functions will have access to your service object:

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

下面是使用$超时而不是$ HTTP表现出。

Here is a Plunker that uses $timeout instead of $http to demonstrate.

这篇关于使用错误的&QUOT AngularJS服务HTTP成功函数;此"范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 22:38