6

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];
                }
            }]
        };
    }
4
  • 1
    Doesn't the else case need to be a deferred.reject() since $auth.isAuthenticated()) will be false? Commented Oct 30, 2015 at 8:47
  • @mindparse if i apply the answer and disable the loadsequence resolve it work. Else it still load the page. Commented Oct 30, 2015 at 9:08
  • shouldnt this be$ocLazyLoad instead of $ocLL or does it work like that also? Commented Nov 6, 2015 at 15:03
  • you can use this $rootScope.$on('$stateChangeError', function(event, toState, toParams, fromState, fromParams, error){ console.log(error) } to log whatever reason the route doesnt resolve, in ui-router all errors reject the resolve. Commented Nov 8, 2015 at 15:50

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

5 Comments

A i see the error you have two resolve, update the answer.
Yes, and I need both. load sequence is to load all dependencies to controller.
I update my answer, when you need two resolve you place both in the same object.
Already tried, it given an error.. Argument 'fn' is not a function, got Object
Update the answer with the correct loadSequence function
0

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');
  }
}

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.