Search code examples
javascriptangularjsresolve

Execute service before AngularJS bootstrap


Currently i would like to figure out, if it is possible to execute a additional service which executes an asynchronous call and bind the response in the current scope and afterwards bootstrapping my application.

I need this behavior, because i wanted to fetch some data from a server and bind this to the scope. I tried some solutions (like the resolve method in the ui-router component) but i couldn't solve it yet.

In addition i wanted to avoid to use the $watch method to observe the variable.

Anyone have a solution for this problem?

Thanks in advance.


Solution

  • Short of writing your own manual bootstrapping, you can't use a service before angular has been bootstrapped. But why do you need to? You can simply fetch the data after angular has bootstrapped, e.g. like Marvin Smit mentions in the comments, fetch it in your controller:

    function MyCtrl($http, $scope) {
        $http.get('whatever')
        .then(function success(response) {
            $scope.stuff = response.data
        })
    }
    

    Angular's directives and interpolation are written with this in mind, and would not error if there's no $scope.stuff defined when the controller is executed.

    Or you could use ngRoute/ui-router and the resolve parameter for a route(see https://docs.angularjs.org/api/ngRoute/provider/$routeProvider)