akcasoy
akcasoy

Reputation: 7215

AngularJS: How to make the initialization of view wait until we get the response from the service?

We have an AngularJS app where we have multiple states, which are defined with ui-router. In one of those states, we need to wait for HTML Initialization until the service responses.

Normally we design our application so that all the service calls run asynchronously, and the views show a loading spinner on the relevant positions. But on this state, we really should/can not show anything to user until the service responses.

How can i define this state, so that it initializes the view only then after the service response?

Our state and component definitions are quite simple:

.state(STATES.details,
  {
    url: "/?ref",
    template: '<app-details></app-details>',
  })

...

.component('details', {
    controller: 'DetailsController as detailsController',
    templateUrl: 'module/details.html'
  }
)

Upvotes: 0

Views: 489

Answers (2)

Bill P
Bill P

Reputation: 3618

Use resolve https://github.com/angular-ui/ui-router/wiki#resolve for that case:

If any of these dependencies are promises, they will be resolved and converted to a value before the controller is instantiated and the $stateChangeSuccess event is fired.

.state(STATES.details,
{
    url: "/?ref",
    component: 'details', // The component's name

    resolve:{

     // Example using function with returned promise.
     // This is the typical use case of resolve.
     // You need to inject any services that you are
     // using, e.g. $http in this example
     promiseObj:  function($http){
        // $http returns a promise for the url data
        return $http({method: 'GET', url: '/someUrl'});
     }

})

Upvotes: 3

Mathew Berg
Mathew Berg

Reputation: 28750

You need to look at using resolve. It can do what you need which will wait for a promise (or multiple)i to finish before loading: https://github.com/angular-ui/ui-router/wiki#resolve

Upvotes: 1

Related Questions