AngularJS multiple resolve

巧了我就是萌 提交于 2019-12-10 13:18:14

问题


This is my ui-router config for a specific route

state('app.merchant', {
                url: '/start/merchant',
                views: {
                    'mainView': {
                        templateUrl: "partials/start_merchant.html"
                    }
                },
                css: ['assets/vendor/bootstrap/dist/css/bootstrap.css','assets/css/styles.css','assets/css/plugins.css'],
                title: 'Buttons',

                resolve: {
                    userRequired: userRequired,
                }

                resolve: loadSequence('flow','angularFileUpload','MerchantWizardCtrl')

            })

The problem is, the page is being displayed even though it doesn't meet the userRequired requirement. This is the function for userRequired:

function userRequired($q, $location, $auth,Account) {
      var deferred = $q.defer();
      if ($auth.isAuthenticated()) {

          Account.getUserStatus()
              .then(function(response){
                if(response.data == true){
                    deferred.resolve();
                }
                  else{
                    deferred.reject();
                }
              })
              .catch(function(response){
                  console.log("Error has occur, Please contact adminstrator");
              });
      } else {
          deferred.resolve();
      }
      return deferred.promise;
    }

How to resolve this? Thanks!!

EDIT

loadsequence:

function loadSequence() {
        var _args = arguments;

        return {
            deps: ['$ocLazyLoad', '$q',
            function ($ocLL, $q) {
                var promise = $q.when(1);
                for (var i = 0, len = _args.length; i < len; i++) {
                    promise = promiseThen(_args[i]);
                }
                return promise;

                function promiseThen(_arg) {

                    if (typeof _arg == 'function')
                        return promise.then(_arg);
                    else
                        return promise.then(function () {
                            var nowLoad = requiredData(_arg);
                            //console.log(nowLoad)
                            if (!nowLoad)
                                return $.error('Route resolve: Bad resource name [' + _arg + ']');
                            return $ocLL.load(nowLoad);
                        });
                }

                function requiredData(name) {
                    if (jsRequires.modules)
                        for (var m in jsRequires.modules)
                            if (jsRequires.modules[m].name && jsRequires.modules[m].name === name)
                                return jsRequires.modules[m];
                    return jsRequires.scripts && jsRequires.scripts[name];
                }
            }]
        };
    }

回答1:


You are not reject the promise when the getUserStatus() services throw an exception (in the .catch()), and also when is not Authenticated must reject, try this solution:

state('app.merchant', {
    url: '/start/merchant',
    views: {
        'mainView': {
            templateUrl: "partials/start_merchant.html"
        }
    },
    css: ['assets/vendor/bootstrap/dist/css/bootstrap.css','assets/css/styles.css','assets/css/plugins.css'],
    title: 'Buttons',
    resolve: {
        userRequired: userRequired,
        loadSequence: loadSequence('flow','angularFileUpload','MerchantWizardCtrl')
    }
})

function userRequired($q, $location, $auth,Account) {
  return $q(function(resolve, reject) {
    if ($auth.isAuthenticated()) {
        Account.getUserStatus()
            .then(function(response){
              if(response.data == true){
                resolve();
              }
                else{
                reject();
              }
            })
            .catch(function(response){
              console.log("Error has occur, Please contact adminstrator");
              reject()
            });
    } else {
        reject()
    }
  });
}

function loadSequence() {
    var _args = arguments;

    return ['$ocLazyLoad', '$q', function ($ocLL, $q) {
            var promise = $q.when(1);
            for (var i = 0, len = _args.length; i < len; i++) {
                promise = promiseThen(_args[i]);
            }
            return promise;

            function promiseThen(_arg) {

                if (typeof _arg == 'function')
                    return promise.then(_arg);
                else
                    return promise.then(function () {
                        var nowLoad = requiredData(_arg);
                        //console.log(nowLoad)
                        if (!nowLoad)
                            return $.error('Route resolve: Bad resource name [' + _arg + ']');
                        return $ocLL.load(nowLoad);
                    });
            }

            function requiredData(name) {
                if (jsRequires.modules)
                    for (var m in jsRequires.modules)
                        if (jsRequires.modules[m].name && jsRequires.modules[m].name === name)
                            return jsRequires.modules[m];
                return jsRequires.scripts && jsRequires.scripts[name];
            }
        }]
}
  • Changed the defer method to the Promise A+ method (i recommend this way).

  • Add the reject() inside the .catch

  • Reject when is not authenticated



回答2:


I think the problem is that you're returning a promise, which by design will allow your app to continue loading while it tries to determine whether UserRequired is valid or not.

So rather than using an asynchronous approach like a promise, just resolve that dependency synchronously and it will prevent the page from loading.

Here's how I would modify UserRequired:

function userRequired($location, $auth, Account) {

  if ($auth.isAuthenticated()) {

      Account.getUserStatus()
          .then(function(response){
            if(response.data == true){
                console.log('Logged in!');
            } else {
                console.log('Not authorized!');
                $location.url('/logout');
            }
          })
          .catch(function(response){
              console.log("Error has occurred, please contact administrator.");
              $location.url('/logout');
          });
  } else {
      console.log('Not authorized!');
      $location.url('/logout');
  }
}



回答3:


First of all, your configuration object has twice the same property :

{
    resolve: {userRequired: userRequired}
    resolve: loadSequence('flow','angularFileUpload','MerchantWizardCtrl')
}

You should have something like :

{
    resolve : {
        userRequired : userRequired,
        loadSequence :    loadSequence('flow','angularFileUpload','MerchantWizardCtrl')
}

Also your catch should return a rejected promise

return $q.reject();

And as said above, reject when not authenticated. You can debug in chrome to make sure all promise are called and return the proper values.



来源:https://stackoverflow.com/questions/33431797/angularjs-multiple-resolve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!