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

How does callback work in AngularJS call to REST service?

本文关键字:REST 服务 工作 调用 AngularJS 回调      更新时间:2023-09-26

我正在研究AngularJS和REST。 代码示例在身份验证函数中重复使用单词callback。"callback"是JavaScript还是Angular中的关键字? 还是callback只是在此代码中创建的自定义变量?

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

下面是模块代码本身:

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;
    });

其他信息

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

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

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

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

这里有很好的解释:

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

callback不是关键字,它只是传递给函数的参数名称,您可以随心所欲地称呼它(callbackcb很常见)。

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

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

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

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

编辑:更具体的例子:

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

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

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

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

编辑:对"附加信息"的回应:

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

函数(身份验证)

参数是否发送一个布尔值,该布尔值确定身份验证中的功能.authenticate()

事情是完全相反的:auth.authenticate()将值传递到"函数(经过身份验证)"中,这是匿名函数。它发生在这一点上:callback && callback(auth.authenticated); - 在.successcallback && callback(false); - 在.error

基本上写成类似

callback && callback(auth.authenticated);

callback && callback(false);

表示如果该callback存在,然后调用它。

简单的例子:

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

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