如何注入服务取决于在其之前运行的脚本的服务



在我的index.html中我有以下代码:

    <script>
        $(document).ready(function () {
                var sessionId = document.URL.substr(document.URL.lastIndexOf('/') + 1);
                $.ajax({
                    url: 'login/' + sessionId + '?format=json',
                    success: function (response) {
                        // if not logged in, then variable is not even defined.
                        console.log(JSON.stringify(response));
                        window.bootstrappedUserObject = response;
                    }
                });
            });
   </script>

当我的服务加载时,我提供的服务如下:

(function() {
"use strict";
var app = angular.module('helloApp.controllers');
app.factory('identity', function($window) {
    var currentUser;
    if (!!$window.bootstrappedUserObject) {
        currentUser = $window.bootstrappedUserObject;
    }
    return {
        currentUser: currentUser,
        isAuthenticated: isAuthenticated,
        isAdministrator: isAdministrator,
        sessionId : sessionId
    };
    function sessionId() {
        return currentUser.sessionId;
    }
    function isAdministrator() {
        return this.currentUser.IsAdmin;
    }
    function isAuthenticated() {
        return !!this.currentUser;
    }
});
})();

我的服务需要以前的脚本运行,否则$ window.bootstrappeduserobject将始终不确定。我如何构建我的电话,以便脚本在开始构建服务之前返回?

对于您的情况,您也可以尝试使用ng-if仅评估指令,一旦$ .ajax结果到达

示例:

html

<div id="overlay" ng-show="!identity.isAuthenticated()" ng-if="Evaluate"><h1 class="centred" style="color:red">Not authenticated</h1></div>

<script>
    $(document).ready(function () {
            var sessionId = document.URL.substr(document.URL.lastIndexOf('/') + 1);
            $.ajax({
                url: 'login/' + sessionId + '?format=json',
                success: function (response) {
                    // if not logged in, then variable is not even defined.
                    console.log(JSON.stringify(response));
                    window.bootstrappedUserObject = response;
                    var appElement = document.querySelector('[ng-app=myApp]');
                    var $scope = angular.element(appElement).scope();
                    $scope.$apply(function() {
                        $scope.Evaluate = true;
                    });
                }
            });
        });
  </script>

最新更新