Using Resolve in Angularjs

Asked

Viewed 170 times

1

I am using resolve to check if the user is logged in as follows:

routeProvider.
//...
.when('/dashboard', {
            title: 'Dashboard',
            templateUrl: 'view/dashboard.html',
            controller: 'authCtrl',
            resolve: {
                auth: function ($q, Session) {
                    var userInfo = Session.getUserInfo();
                    if (userInfo) {
                        return $q.when(userInfo);
                    } else {
                        return $q.reject({ authenticated: false });
                    }
                }
            }
        })

My question is, what does the $q. when(userinfo); in the code above?

From what I understand, I should pass the variable "userinfo" as parameter in the event "routeChangeSucess", right?

app.run(["$rootScope", "$location", 
  function ($rootScope, $location) {

    $rootScope.$on("$routeChangeSuccess", function (userInfo) {
        console.log(userInfo);
    });
    //...

Note that I have in the code above a console.log, but when checking the Firefox console, does not return me the user data but the following:

Object { name="$routeChangeSuccess", targetScope=h, defaultPrevented=false, more...}

What is wrong?

1 answer

0


Actually what’s wrong are the parameters of $routeChangeSuccess, they must be:

$rootScope.$on("$routeChangeSuccess", function(event, current, previous) {

That’s why the log shows this object:

Object { name="$routeChangeSuccess", targetScope=h, defaultPrevented=false, more...}

About the $q.when, he does nothing more than receive a Promise or any object and return a Promise.
If this object is not a Promise, the when makes a wrap his in a Promise and calls the resolve.

  • Note that in "resolve" I created the object "userinfo", as I do to access the object in the routeChangeSuccess?

  • I suggest changing the parameters to: (event, args) and debug with the console the contents of args to see where your userinfo.

  • Right, it is in the second parameter, locals -> auth, auth has been defined in "resolve".

  • Glad you solved your problem. I hope if you don’t accept this as the correct answer, at least signal as useful. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.