bryan
bryan

Reputation: 9369

Angularjs Passing variable through resolve function

Right now I have a Auth Factory set up to run when my State goes to cloud. I am trying to pass the :cloud_id to that authCheck() function but I don't know how.

Could anyone point me in the right direction to change this:

resolve: { authenticated: authenticated }

To something like this:

resolve: { authenticated: authenticated(cloud_id) }

Here is my code:

.factory('Auth', function($http, $state, $q) {

    var factory = { authCheck: authCheck };
    return factory;

    function authCheck(cloud_id) {
        return $http.post('/auth/check', {id:cloud_id});
    }

})
.config(function($stateProvider, $urlRouterProvider, $locationProvider) {

    $locationProvider.html5Mode(true);
    $urlRouterProvider.otherwise('/cloud');

    var authenticated = ['$q', 'Auth', '$rootScope', function ($q, Auth, $rootScope) { 
        var deferred = $q.defer();
        Auth.authCheck(cloud_id).then(function(){ deferred.resolve(); }, function(){ deferred.reject(); });
        return deferred.promise;
    }];

    $stateProvider

        .state('cloud', {
            url: '/cloud/:cloud_id',
            templateUrl: 'pages/templates/cloud.html',
            controller: 'cloud',
            resolve: { authenticated: authenticated }
        })

})

Upvotes: 6

Views: 3123

Answers (1)

Reto Aebersold
Reto Aebersold

Reputation: 16624

You can inject and use the $stateParams like this:

var authenticated = ['$q', 'Auth', '$rootScope', '$stateParams', function ($q, Auth, $rootScope, $stateParams) { 
    var deferred = $q.defer();
    Auth.authCheck($stateParams.cloud_id).then(function(){ deferred.resolve(); }, function(){ deferred.reject(); });
    return deferred.promise;
}];

See this plnkr.

Upvotes: 3

Related Questions