Javascript 回调如何在 AngularJS 调用 REST 服务中工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34821978/
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-08-23 16:54:48  来源:igfitidea点击:

How does callback work in AngularJS call to REST service?

javascriptangularjs

提问by CodeMed

I am studying AngularJS and REST. A code sample uses the word callbackrepeatedly in an authentication function. Is "callback" a keyword in JavaScript or Angular? Or is callbackjust a custom variable created in this code?

我正在学习 AngularJS 和 REST。代码示例callback在身份验证函数中重复使用该词。“回调”是 JavaScript 还是 Angular 中的关键字?或者callback只是在此代码中创建的自定义变量?

How does callbackwork in the code below? Googling callbackand AngularJS is not producing usable results. The code for the AngularJS module in question can be read at this link, which also contains all the code for the sample app.

callback在下面的代码中如何工作?谷歌搜索callback和 AngularJS 没有产生可用的结果。 相关 AngularJS 模块的代码可以在此链接中阅读,其中还包含示例应用程序的所有代码。

Here is the module code itself:

这是模块代码本身:

angular.module('auth', []).factory( 'auth',

    function($rootScope, $http, $location) {

        enter = function() {
            if ($location.path() != auth.loginPath) {
                auth.path = $location.path();
                if (!auth.authenticated) {
                    $location.path(auth.loginPath);
                }
            }                   
        }

        var auth = {

            authenticated : false,

            loginPath : '/login',
            logoutPath : '/logout',
            homePath : '/',
            path : $location.path(),

            authenticate : function(credentials, callback) {

                var headers = credentials && credentials.username ? {
                    authorization : "Basic "
                            + btoa(credentials.username + ":"
                                    + credentials.password)
                } : {};

                $http.get('user', {
                    headers : headers
                }).success(function(data) {
                    if (data.name) {
                        auth.authenticated = true;
                    } else {
                        auth.authenticated = false;
                    }
                    callback && callback(auth.authenticated);
                    $location.path(auth.path==auth.loginPath ? auth.homePath : auth.path);
                }).error(function() {
                    auth.authenticated = false;
                    callback && callback(false);
                });

            },

            clear : function() {
                $location.path(auth.loginPath);
                auth.authenticated = false;
                $http.post(auth.logoutPath, {}).success(function() {
                    console.log("Logout succeeded");
                }).error(function(data) {
                    console.log("Logout failed");
                });
            },

            init : function(homePath, loginPath, logoutPath) {

                auth.homePath = homePath;
                auth.loginPath = loginPath;
                auth.logoutPath = logoutPath;

                auth.authenticate({}, function(authenticated) {
                    if (authenticated) {
                        $location.path(auth.path);
                    }
                })

                // Guard route changes and switch to login page if unauthenticated
                $rootScope.$on('$routeChangeStart', function() {
                    enter();
                });

            }

        };

        return auth;

    });

Additional information

附加信息

Based on @okonyk's response, I am including code from a different module that calls the auth.authenticate() function:

根据@okonyk 的回复,我包含了来自调用 auth.authenticate() 函数的不同模块的代码:

$scope.login = function() {
    auth.authenticate($scope.credentials, function(authenticated) {
        if (authenticated) {
            //do some stuff
             $scope.error = false;
         } else { 
            $scope.error = true;
        }
    })
}

So how does the call from login()to auth.authenticate($scope.credentials, function(authenticated)work? Is the function(authenticated)parameter sending a boolean that determines functionality inside auth.authenticate()? For example true might indicate to do the callback, while false might indicate note to do the callback, but it would help to have it explained.

那么从login()to调用是如何auth.authenticate($scope.credentials, function(authenticated)工作的呢?function(authenticated)参数是否发送确定内部功能的布尔值auth.authenticate()?例如,true 可能表示进行回调,而 false 可能表示注意进行回调,但解释一下会有所帮助。

You can read the code in the sample app for the other module with the login()method by clicking on this link.

您可以login()通过单击此链接,使用该方法阅读示例应用程序中其他模块的代码

回答by oKonyk

Hereis pretty good explanation:

这里有一个很好的解释:

A callback function, also known as a higher-order function, is a function that is passed to another function (let's call this other function “otherFunction”) as a parameter, and the callback function is called (or executed) inside the otherFunction. A callback function is essentially a pattern (an established solution to a common problem), and therefore, the use of a callback function is also known as a callback pattern.

回调函数,也称为高阶函数,是将函数作为参数传递给另一个函数(让我们称这个另一个函数为“otherFunction”),并在 otherFunction 内部调用(或执行)回调函数。回调函数本质上是一种模式(对常见问题的既定解决方案),因此,回调函数的使用也称为回调模式。

callbackis not a keyword, its just a name of parameter that is passed into the function, you can call it whatever you want (callbackor cbis pretty common).

callback不是关键字,它只是传递给函数的参数名称,您可以随意调用它(callback或者cb很常见)。

I'll try to explain it on example of super simplistic custom build callback function:

我将尝试以超级简单的自定义构建回调函数为例进行解释:

function useAsCallback(string){
  console.log("callback is being executed with passed parameter: " + string)
}

function main(param, callback){
  callback(param)
}

main(123456, useAsCallback)

if you run this, it would print: callback is being executed with passed parameter: 123456

如果你运行这个,它会打印: callback is being executed with passed parameter: 123456

Callback pattern is commonly used to handle JavaScript asynchronous behavior.

回调模式通常用于处理 JavaScript 异步行为。

EDIT:more specific example:

编辑:更具体的例子:

Talking about your code snippet...lets say you'll inject your factory into controller.

谈论您的代码片段...假设您将工厂注入控制器。

Now you have auth.authenticatemethod exposed. You have to pass two parameters(credentials, callback).

现在你已经auth.authenticate公开了方法。你必须传递两个参数(credentials, callback)

auth.authenticate({username: Joe, password: 123456}, function(authStatus){
  if(authStatus){
    console.log("Successfully authenticated")
  }else{
    console.log("Access denied")
  }
});

We just passed anonymous function as a callbackparameter of our auth.authenticatemethod.

我们只是传递匿名函数作为callback我们auth.authenticate方法的参数。

EDIT:responce to 'ADDITIONAL INFORMATION':

编辑:对“附加信息”的回应:

It looks like there might be some misunderstanding. You are asking:

看来可能有些误会了。你在问:

Is the function(authenticated) parameter sending a boolean that determines functionality inside auth.authenticate()

function(authenticated) 参数是否发送一个布尔值来确定 auth.authenticate() 中的功能

Thing is that, it is complete opposite: auth.authenticate()passes value into 'function(authenticated)', which is anonymous function. It happens at this point: callback && callback(auth.authenticated);- on .successor callback && callback(false);- on .error

事实是,它完全相反:auth.authenticate()将值传递给“函数(已验证)”,这是匿名函数。它发生在这一点上:callback && callback(auth.authenticated);- on.successcallback && callback(false);- on.error

回答by Mr. Baudin

Basically writing something like

基本上写类似的东西

callback && callback(auth.authenticated);

or

或者

callback && callback(false);

means that if that callbackexists and then calls it.

意味着如果callback存在,然后调用它。

simple example:

简单的例子:

function foo () {
   console.log('foo');
   return 'Fighting foo!';
}

foo && foo();

It is just a language construct, a weird one and not a great practice for readability. This code also implies that the result of calling foo()should be valid but this is never handled. I'd use a simple ifstatement.

它只是一种语言结构,一种奇怪的结构,并不是提高可读性的好方法。这段代码还暗示调用的结果foo()应该是有效的,但这永远不会被处理。我会用一个简单的if语句。