1

I basically need to call a server that's will return me a JSON structure before load the controller.

I was using many methods to archive that, but it's not working. It's don't show me any error and the page got blank. Any clue about what's going on ?

This is my controller..

angular
.module('app',[
    'ngAnimate',
    'ui.router',
    'ui.bootstrap',
    'ngCookies'
])
.run(function($rootScope) {
    $rootScope.backendServer = "http://localhost:5000/";
})
.config(['$urlRouterProvider','$stateProvider', function($urlRouterProvider,$stateProvider) {
    $stateProvider
        .state('cms',{
            url: '/my',
            templateUrl: './app/templates/my.html',
            controller : 'my',
            resolve: {
                dbState: function ($q) {
                    var defer = $q.defer();
                    Database.check().then(function (s) {
                        defer.resolve(s);
                    });
                    return defer.promise;
                }
            }
        })
}])
.controller(function ($scope){

})

...and this is my service:

angular
.module('app')
.factory('Database',['$http', '$rootScope','$q', function($http, $rootScope, $q) {
    return {
        check: function () {
            var call = $rootScope.backendServer + 'cms/database/check';
            return $http.get(call);
        }
    }
}]);
3
  • does program get into then ? Database.check().then(function (s) { defer.resolve(s); }); Commented Apr 27, 2017 at 10:42
  • You forgot to inject Database factory to the resolve function, also avoid promise anti patterns Commented Apr 27, 2017 at 10:43
  • you mean..I need to build promises on the controller and on the resolver at the same time ? Commented Apr 27, 2017 at 10:43

1 Answer 1

3

don't create a defer object when you already returning a promise. so remove the defer and just return the factory function

also, inject the Database service to resolve

 resolve: {
     dbState: function(Database) {

         return Database.check()
     }
 }

In the controller catch it like this

.controller("ctrl", function($scope, dbState) {
    console.log(dbState.data)

})

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Almost there...everything looks good, but dbState.then(function(response) { console.log(response) }) - throw me a dbState.then is not a function
can you create a plnkr or something
my bad. remove the then function.check the updated answer

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.