3

已经问过这个主题,但我不知道在我的情况下该怎么做。

使用AngularJS 1.0.5

在显示视图“登录”之前,我想在未从 AJAX 请求加载数据时获取一些数据并延迟视图呈现。

这是主要代码。这是好方法吗?

angular.module('tfc', ['tfc.config', 'tfc.services', 'tfc.controllers']).config([
 '$routeProvider', '$locationProvider', '$httpProvider',
 function($routeProvider, $locationProvider, $httpProvider) {
  $routeProvider.when('/login', {
    templateUrl: 'views/login.html',
    controller: "RouteController",
    resolve: {
      data: function(DataResolver) {
        return DataResolver();
      }
    }
  });
}
]);

module_services = angular.module("tfc.services", []);

module_services.factory("DataResolver", [
 "$route", function($route) {
  console.log("init");
  return function() {
    // Tabletop is a lib to get data from google spreadsheets
    // basically this is an ajax request
    return Tabletop.init({
      key: "xxxxx",
      callback: function(data, tabletop) {
        console.log("[Debug][DataResolver] Data received!");
        return data;
      }
    });
  };
 }
]);
4

2 回答 2

1

The point of AngularJS is that you can load up the templates and everything and then wait for the data to load, it's meant to be asynchronous.

Your view should be using ng-hide, ng-show to check the scope of the controller so that when the data in the scope is updated, the view will display. You can also display a spinner so that the user doesn't feel like the website has crashed.

于 2014-07-31T23:53:31.593 回答
1

回答这个问题,在呈现视图之前显式加载数据的方式似乎是正确的。请记住,它可能不会提供最佳体验,因为需要一些时间来解决这个问题,可能会给人一种您的应用停止了一段时间的印象。

请参阅John Pappa 博客中的示例,以在使用 Angular 的默认路由器解析路由之前加载一些数据:

// route-config.js
angular
    .module('app')
    .config(config);

function config($routeProvider) {
    $routeProvider
        .when('/avengers', {
            templateUrl: 'avengers.html',
            controller: 'Avengers',
            controllerAs: 'vm',
            resolve: {
                moviesPrepService: function(movieService) {
                    return movieService.getMovies();
                }
            }
        });
}

// avengers.js
angular
    .module('app')
    .controller('Avengers', Avengers);

Avengers.$inject = ['moviesPrepService'];
function Avengers(moviesPrepService) {
    var vm = this;
    vm.movies = moviesPrepService.movies;
}

您基本上使用resolve路由上的参数,以便 routeProvider 在实例化控制器之前等待所有承诺得到解决。有关更多信息,请参阅文档

于 2015-07-14T19:38:23.713 回答