Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

})
like image 817
bryan Avatar asked Oct 20 '22 12:10

bryan


1 Answers

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.

like image 177
Reto Aebersold Avatar answered Oct 29 '22 19:10

Reto Aebersold