Angular:等待app运行以获得响应

时间:2015-10-23 13:41:19

标签: angularjs authentication

截至this post,我试图弄清楚用户是否已登录(使用基于令牌的身份验证)。

该计划如下:

1 /加载页面,调用app run,并将authenticated设置为false作为默认值

app.run(function($http, UserService) {
    UserService.requestCurrentUser();

    $http.defaults.xsrfHeaderName = 'X-CSRFToken';
    $http.defaults.xsrfCookieName = 'csrftoken';
});

app.constant('AUTHENTICATED', false);

2 / UserService调用其方法requestCurrentUser(),其中http get被发送到正确的url,其标头中包含令牌。

  • 如果令牌正确,则会向用户发回(成功案例,我们已经过身份验证)。
  • 如果没有,我收到权限错误(错误情况,我们未经过身份验证)。

这会更新currentUser属性和AUTHENTICATED常量。

app.factory('UserService', function ($http, $q, $window, AUTHENTICATED) {
    var _currentUser = {};

    return {

        getCurrentUser: function() {
            return _currentUser;
        },

        setCurrentUser: function(user) {
            _currentUser = user;
        },

        requestCurrentUser: function() {
            return $http.get('/accounts/api/').then(
                function (response) {
                    _currentUser = response.data;
                    AUTHENTICATED = true;
                },
                function (error) {
                    AUTHENTICATED = false;
                }
            );
        },
    };
});

3 /调用Controller并更新authenticatedcurrentUser范围值。

app.controller('AuthCtrl', function ($scope, AuthService, UserService, AUTHENTICATED) {
    $scope.authenticated = AUTHENTICATED;
    $scope.currentUser = UserService.getCurrentUser();
});

问题是控制器尝试在requestCurrentUser方法(在app运行中启动)收到响应之前达到值。那么我应该在哪里启动requestCurrentUser以获得预期的行为?

由于

1 个答案:

答案 0 :(得分:0)

您可以做什么将您的用户状态对象包装在父对象中。例如:

$("<a>", {
  text: channel,
  href: '#'
})

然后在你的控制器内:

//New Flag for XDomainRequest is being used or Not
var isXDomain = false;
//Establish Reference to script
var self = this;
//Set Your XML Path here
var xml_link = "";
//XML Object which comes after loading XML successfully
var objXml;

function startXMLLoading() {
    //Create New Request
    if (window.XDomainRequest) {
        //This Code runs in IE9, IE10, IE11
        xhttp = new XDomainRequest();
        isXDomain = true;
        //XDomainRequest runs Synchronously, So onload function is necessary
        xhttp.onload = function() {
            var parser = new DOMParser();
            var xmlDoc = parser.parseFromString(xhttp.responseText, "text/xml");
            objXml = xmlDoc;
            //Handle XML Response
            handleXML(objXml);
        };
        xhttp.onerror = function() {};
        xhttp.onprogress = function() {};
        xhttp.open("get", xml_link);
        xhttp.send();

    } else if (window.XMLHttpRequest) {
        //Runs in advanced browsers like Chrome, Firefox, Safari
        xhttp = new XMLHttpRequest();
    } else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    if (!isXDomain) {
        try {
            //Open Get Request , Synchronous
            xhttp.open("GET", xml_link, true);
            //Callback
            xhttp.onreadystatechange = function() {
                    if (xhttp.readyState == 4) {
                        //Establish Reference to XML Response
                        objXml = xhttp.responseXML;
                        //Handle XML Response
                        handleXML(objXml);
                    }
                }
                //Send Request
                xhttp.send();
        } catch (e) {
            console.log("err : " + e);
        }
    }
}

//function for parsing XML object
function handleXML(sXml) {
    //Use Following Syntax to get values of XML Element and Attributes.
    //Only Following Syntax works across all Browsers including IE9, IE10, IE11
    //Syntax like sXml.getElementsByTagName("dataset")[0].children[0].innerHTML doesnot work in IE9,10,11 Browsers 
    //sXml.getElementsByTagName("dataset")[0].childNodes[0].nodeValue;
    //sXml.getElementsByTagName("dataset")[0].childNodes[0].getAttribute('voteField');    
}

//window.onload = function(){
startXMLLoading();
//}

这样,当您的用户更新时(无论您的服务何时或如何),绑定到该状态的任何内容都将收到更新。因此,当控制器可用时,您的控制器将可以访问var state = { _currentUser: {} }; return { getUserState: function(){ return state; } };