daan.desmedt
daan.desmedt

Reputation: 3820

Init application waiting for REST call data result

Having created some basic web applications with Angular, still learning and discovering ...

I need to create a Angular application which depends on various parameters used in the application. For example various label string we will retrieve through REST... These labels are used on every screen of the application, including the first screen that is shown on start-up...

I'm looking for a 'proper' / 'good' / 'angular' way to init the application waiting for the result of a sort of 'init-application' rest-call - due to the fact that the result of this rest call contains data the application will need from start on, I have found an example approach below ...

https://blog.mariusschulz.com/2014/10/22/asynchronously-bootstrapping-angularjs-applications-with-server-side-data

Are there any more ideas / thoughts / useful links ... Thanks!

Upvotes: 0

Views: 273

Answers (1)

Kumar Sambhav
Kumar Sambhav

Reputation: 7765

I would suggest you to explore the 'resolve' property of ngRoute(if you are using ngRoute) or UI-router state:-

While using $routeProvider:-

$routeProvider
    .when("/news", {
        templateUrl: "newsView.html",
        controller: "newsController",
        resolve: {
            message: function(messageService){
                return messageService.getMessage();
        }
    }
})

Or, if you are using UI Router :-

$stateProvider.state('root',{
        abstract:true, // this is abstract statte, controller is in child states.
        templateUrl:'/assets/root-module/partial/main/main.html',
        resolve : {
            securityContext : function($http){
                return $http.get("/security/context");
            },
            token : function(securityService,securityContext){
                securityService.setToken(securityContext.data.token);
                console.debug(securityContext.data.token);
                return securityContext.data.token;
            }
        }
    });

In either of the approaches, just make sure that you DO NOT provide 'ng-controller' in your HTML templates. Rather provide the controller while defining your route|state as the above example suggests.

The properties being "resolved" - if they are promises, the controller (hence the view) won't be initialized until the promise is resolved.

I highly recommend you to explore UI Router state hierarchy approach that allows you to share 'resolved; proerties to the child states.

Upvotes: 2

Related Questions