AngularJS: 如何让视图的初始化等到我们得到服务的响应?

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

我们有一个 AngularJS 应用程序,其中有多个状态,用 ui-router 定义。在其中一种状态下,我们需要等待 HTML 初始化,直到服务响应。

通常我们设计我们的应用程序,以便所有服务调用 运行 异步,并且视图在相关位置显示加载微调器。但是在这种状态下,我们真的 should/can 在服务响应之前不会向用户显示任何内容。

如何定义此状态,以便它仅在服务响应后才初始化视图?

我们的状态和组件定义很简单:ui

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

...

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

在这种情况下使用 resolve https://github.com/angular-ui/ui-router/wiki#resolve

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

})

你需要看看使用resolve。它可以做你需要的,在加载之前等待一个承诺(或多个)i 完成:https://github.com/angular-ui/ui-router/wiki#resolve