回调如何在AngularJS中调用REST服务? [英] How does callback work in AngularJS call to REST service?

查看:54
本文介绍了回调如何在AngularJS中调用REST服务?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究AngularJS和REST。代码示例在身份验证功能中重复使用单词 callback 回调是JavaScript或Angular中的关键字吗?或者回调只是在此代码中创建的自定义变量? 回调如何在下面的代码中工作? Google搜索回调并且AngularJS没有产生可用的结果。 可以在此链接上阅读相关AngularJS模块的代码,其中还包含示例应用程序的所有代码。

I am studying AngularJS and REST. A code sample uses the word callback repeatedly in an authentication function. Is callback a keyword in JavaScript or Angular? Or is callback just a custom variable created in this code? How does callback work in the code below? Googling callback and 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.

这是模块代码本身:

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()函数的不同MODULE的代码:

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

$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) work?是 function(authenticated)参数发送一个确定 auth.authenticate()内部功能的布尔值?如果是,你可以明确吗?我可以将它拼凑在一起。例如,true可能表示要执行callba ck,虽然false可能表示要做回调的注释,但这有助于解释它。 您可以通过单击此链接,使用 login()方法读取其他模块的示例应用程序中的代码。 / p>

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()? If so, can you please be explicit? I can piece it together. 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. You can read the code in the sample app for the other module with the login() method by clicking on this link.

推荐答案

这里是非常好的解释:


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

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.

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

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

我会试试在超简单的自定义构建回调函数的例子中解释它:

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)

如果你运行它,它会打印:
正在使用传递的参数执行回调:123456

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

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

Callback pattern is commonly used to handle JavaScript asynchronous behavior.

编辑:更具体的例子:

谈论您的代码片段...... 让我们说你将你的工厂注入控制器。

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

现在你有 auth.authenticate 方法暴露。您必须传递两个参数(凭据,回调)

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

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

我们刚刚通过匿名函数作为回调我们的 auth.authenticate 方法的参数。

We just passed anonymous function as a callback parameter of our auth.authenticate method.

编辑:响应'其他信息':

看起来可能存在一些误解。你问:

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


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

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

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

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 .success or callback && callback(false); - on .error

这篇关于回调如何在AngularJS中调用REST服务?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆