javascript 如何将值传递给 AngularJS $http 成功回调

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19116815/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:25:54  来源:igfitidea点击:

How to pass a value to an AngularJS $http success callback

javascriptangularjscallback

提问by Team AIGD

In my AngularJS application I am doing the following

在我的 AngularJS 应用程序中,我正在执行以下操作

$http.get('/plugin/' + key + '/js').success(function (data) {
    if (data.length > 0) {
        console.log(data);
        // Here I would also need the value of 'key'
    }
});

Now I need to access the keyvalue within the success callback, i.e. I need to know which value it had when the get()request has been made.

现在我需要访问key成功回调中的值,即我需要知道在get()发出请求时它具有哪个值。

Any "best practice" how to do so?

任何“最佳实践”怎么做?

PS: I can do the following, but is there a better way?

PS:我可以执行以下操作,但是有更好的方法吗?

var key = config.url.split('/')[2];

回答by geniuscarrier

Solution 1:

解决方案1:

$scope.key = key;
$http.get('/plugin/' + key + '/js').success(function (data) {
    if (data.length > 0) {
        console.log(data, $scope.key);
    }
});

Solution 2 (Updated per Jim Hong's observation in his answer):

解决方案 2(根据 Jim Hong 在他的回答中的观察更新):

$http.get('/plugin/' + key + '/js').success((function(key) {
    return function(data) {
        console.log(key, data);
    }
})(key));

回答by Jim Horng

Reference to @geniuscarrier The working solution on my side is

参考@geniuscarrier 我这边的工作解决方案是

$http.get('/plugin/' + key + '/js').success((function(key) {
    return function(data) {
        console.log(key, data);
    }
})(key));

Since using @geniuscarrier, I'l get

自从使用@geniuscarrier,我会得到

data undefined error

数据未定义错误

.

.

回答by watashiSHUN

Technically speaking, this is not an AngularJS problem but a feature of javascript

从技术上讲,这不是 AngularJS 的问题,而是javascript 的一个特性

first of all, functionsthat you defined inside a scopewill have access to local variableand parameterof its parentscope

首先,功能,你一个内部定义的范围将有机会获得局部变量参数母公司范围

function parent(arg){
   var local
   function child(){
       // have access to arg and local
   }
}

Scope actually works well with the parent-child analogy: if you are the parent and you owna cookie, of cause you are welling to share it with your children...but if you are a kid...your cookie is yourcookie, your parent is not allowed to touch it :). In other words, inner scope can access outer scope but it does not work both ways

Scope 实际上适用于亲子类比:如果你是父母并且你拥有一个 cookie,因为你很乐意与你的孩子分享它......但如果你是一个孩子......你的 cookie 就是你的cookie ,你的父母不允许碰它:)。换句话说,内部作用域可以访问外部作用域,但不能双向工作

So you should definitely be able to do:

所以你绝对应该能够做到:

$http.get('/plugin/' + key + '/js').success(function (data) {
    if (data.length > 0) {
        console.log(data, key); //as long as you can pass it to $http.get as an argument
                                //you can access it here
    }
});

Secondly, because of the event-driven nature of javascript,inner function store referencesto the outer function's variables. you probably have heard of this

其次,由于 javascript 的事件驱动特性,内部函数存储外部函数变量的引用。你可能听说过这个

functions in javascript are objects

javascript中的函数是对象

local variables and parameters are thus private members of the function:

因此局部变量和参数是函数的私有成员:

function ObjectA(){ // define a constructor
    var x = 10      // private variable
    changeX : function(){
                  x = 20   // access and MODIFY a variable of parent scope
              }
}

if you can understand how private variable works in javascript, then you basically understand what closureis. Thus, for call back function, it is very possible that by the time it is triggered, the value of the parent scope variable is already changed. To fix this, you can use an Immediately Invoked Function Expression(IIFE)

如果你能理解私有变量在 javascript 中是如何工作的,那么你基本上就理解了什么是闭包。因此,对于回调函数,很有可能在它被触发时,父作用域变量的值已经改变了。要解决此问题,您可以使用立即调用函数表达式(IIFE)

$http.get('/plugin/' + key + '/js').success((function(currentKeyValue) {
    return function(data) {
        console.log(currentKeyValue, data);
        // again, currentKeyValue is a REFERENCE to outer function's
        // parameter. However, since String is passed by value in javascript
        // currentKeyValue of outer scope is a DIFFERENT string that has the
        // same value as KEY when it is invoked
    }
})(key)); // immediately invoke the function passing the key as a parameter

回答by coderHASH64codingHASH46code

Instead of polluting scope or complicating with iif, another cleaner way is to create a callback function and call it with parameters;

另一个更简洁的方法是创建一个回调函数并带参数调用它,而不是污染作用域或使 iif 复杂化;

var myCallBack = function (key) {
  return function (data) {
    if (data.length > 0) {
      console.log(data, key);
    }
  }
}

$http.get('/plugin/' + key + '/js').success(myCallBack(key));

回答by george007

Phew, I was looking for this answer for so long, but it's good it is here. Just to update it, since legacy promise methods successand errorhave been deprecated and we should use the standard thenmethod instead.

呼,我一直在寻找这个答案,但它在这里很好。只是为了更新它,因为传统方法的承诺success,并error已被弃用,我们应该使用标准then方法来代替。

Solution 2 in @geniuscarrier and @jim-horng answers may be rewritten like this:

@geniuscarrier 和 @jim-horng 答案中的解决方案 2 可以这样重写:

$http.get('/plugin/' + key + '/js').then(
    (function(key) {
        return function(data) {
            console.log(key, data);
        }
    })(key),
    function(data) {
        //error handle
    });