等待异步任务完成在启动Angular JS之前

时间:2016-08-11 15:56:20

标签: javascript angularjs ionic-framework ibm-mobilefirst

我使用MobileFirst v8和Ionic v1.3.1构建应用程序。当应用程序启动时,我在app.js文件

中有常规的离子角度代码

这是app.js

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    ...
  })
.controller('IndexCtrl', function($scope, $state) {
    RememberMeService.checkIfLoggedIn().success(function(data) {
        alert("YAY!!");
    }).error(function(data) {
        alert('fail :(');
    });

});

function wlCommonInit() {
var serverUrl = WL.App.getServerUrl(function(success){
    console.log(success);
}, function(fail){
    console.log(fail);
});

WLAuthorizationManager.obtainAccessToken().then(
    function (accessToken) {
        console.log(">> Success - Connected to MobileFirst Server");       
    },
    function (error) {
        console.log(">> Failed to connect to MobileFirst Server");  
        console.log(error);        
    }
);

这是RememberMeService

.service('RememberMeService', function($q) {
return {
    checkIfLoggedIn: function() {
        var deferred = $q.defer();
        var promise = deferred.promise;
        var securityCheckName = 'UserLogin';

        WLAuthorizationManager.obtainAccessToken(securityCheckName).then(
                function (accessToken) {
                    console.log('USER IS LOGGED IN!!!');
                },
                function (response) {
                    console.log("obtainAccessToken onFailure: " + JSON.stringify(response));
            }
        );

        promise.success = function(fn) {
            promise.then(fn);
            return promise;
        }
        promise.error = function(fn) {
            promise.then(null, fn);
            return promise;
        }

        return promise;

    }
}
})

当前发生的事情是在此行WLAuthorizationManager.obtainAccessToken(securityCheckName).then失败时调用RememberMeService,因为它表示WLAuthorizationManager未定义。它未定义,因为wlCommonInit()中的app.js函数尚未完成,它是异步函数。

那么在wlCommonInit()函数完成并定义WLAuthorizationManager之前,如何延迟调用控制器或服务?

感谢您的帮助

修改

这是我的新function wlCommonInit() {

function wlCommonInit() {
var serverUrl = WL.App.getServerUrl(function(success){
    console.log(success);
}, function(fail){
    console.log(fail);
});

WLAuthorizationManager.obtainAccessToken().then(
    function (accessToken) {
        console.log(">> Success - Connected to MobileFirst Server"); 
        angular.bootstrap(document.getElementById('indexBody'), ['app']);
    },
    function (error) {
        console.log(">> Failed to connect to MobileFirst Server");  
        console.log(error);        
    }
);

我的index.html是

<body id="indexBody">
    <h1>test</h1>
</body>

我收到错误

kError in Success callbackId: WLAuthorizationManagerPlugin887134242 : Error: [$injector:modulerr] Failed to instantiate module ng due to:
TypeError: Cannot set property 'aHrefSanitizationWhitelist' of null

我正在做正确的引导

1 个答案:

答案 0 :(得分:0)

您可以在wlCommonInit成功回调中手动引导角度应用。有关详细说明,请参阅https://docs.angularjs.org/guide/bootstrap#manual-initialization