【问题标题】:AngularJS routes and Ajax data on route changeAngularJS 路由和关于路由更改的 Ajax 数据
【发布时间】:2014-09-23 03:23:55
【问题描述】:

我无法理解执行以下操作的 Angular 方式...

我配置了一个路由器,一旦更改了路由并提供了 templateUrl,我想进行 Ajax 调用以获取一些 JSON 数据。

请注意,我不想等待获取模板,而是使用控制器获取 JSON 数据,因为这是两个串行 HTTP 调用。我想在获取模板的同时获取 JSON 数据。有没有众所周知的模式可以做到这一点?

如果我错了,请纠正我...现在,我知道我应该使用解析器,在该解析器中我将调用“数据提供者”,它将触发 HTTP 调用以获取 JSON 数据。该数据将提供给控制器。所以像这样......

app.config(['$routeProvider', 'data', function( routeProvider, dataProvider ) {

  routeProvider.
      when('/reports/:reportName', {
          templateUrl: function( urlData ) {
              return "/some/url/" + urlData.reportName + "/content";
          },
          resolve: {
              reportData: function() {
                  return dataProvider.getData();
              }
          },
          controller: 'reportRoutingCtrl'
      });
}]);
app.controller('reportRoutingCtrl', ['$scope', 'reportData', 'reportName', function( scope, reportData ) {
    console.dir( reportData );
}]);

这是正确的模式吗?如果是这样,我如何才能访问解析器中的“urlData”对象?

谢谢你的帮助!!

【问题讨论】:

  • 是的,没关系...$routeParams 获取您的urlData

标签: ajax json angularjs user-interface angular-routing


【解决方案1】:

这就是我的做法(我认为这是最被接受的做法)。

假设您正在渲染一个视图,用户可以在其中可视化一个具体项目,并且您必须从服务器获取该项目的数据。

我会有一个像这样的service

services.factory('ItemLoader', ['Item', '$route', '$q',
    function(Item, $route, $q) {
  return function() {
    var delay = $q.defer();
    Item.get({id: $route.current.params.itemId}, function(item) {
      delay.resolve(item);
    }, function() {
      delay.reject('Unable to fetch the item'  + $route.current.params.itemId);
    });
    return delay.promise;
  };
}]);

我的routeProvider 看起来像这样:

  .when('/view/:itemId', {
    controller: 'ViewCtrl',
    resolve: {
      item: ["ItemLoader", function(ItemLoader) {
        return ItemLoader();
      }]
    },
    templateUrl:'/views/viewItem.html'
  })

控制器的签名是这样的:

app.controller('ViewCtrl', ['$scope', '$location', 'item',
function($scope, $location, item) {
   ...
}]);

请注意,解析会将获取的item 注入到控制器中。

【讨论】:

  • 感谢您的回复,我错过了您可以将依赖项注入解析函数的事实。我最初的沮丧是因为除了提供者之外,我无法向配置函数注入任何东西。用于获取数据的提供者有点太多了。我也喜欢你的工厂如何返回一个新的承诺,然后注入控制器。非常感谢您写这篇文章并为我解决问题!
  • @AssafMoldavsky 没问题!随时! ;)
【解决方案2】:

总结 Josep 提供的内容并将其放入最终解决方案中,以下是代码,以防其他人对此感到疑惑...

services.factory('dataProviderService', ['$route', '$q', '$http', function( $route, $q, $http ) {

    return function() {
        getReportData: function( reportName ) {
            var delay = $q.defer();

            $http({method: 'GET', url: "someURL", params: {
                fileId: "11159",
                reportName: "someName"
            }}).success( function(data, status, headers, config) {

                // this callback will be called asynchronously
                // when the response is available
                delay.resolve( data );

            }).error( function(data, status, headers, config) {

                // called asynchronously if an error occurs
                // or server returns response with an error status.
                delay.reject( data );

            });

            return delay.promise;
        }
    };
}]);
app.config(['$routeProvider', 'data', function( routeProvider, dataProvider ) {

    routeProvider.
        when('/reports/:reportName', {
            templateUrl: function( urlData ) {
                return "/some/url/" + urlData.reportName + "/content";
          },
        resolve: {
            reportName: ['$route', function( route ) {
                return route.current.params.reportName;
            }],
            reportData: ['reportService', '$route', function( reportService, $route ) {
                var reportName = $route.current.params.reportName;
                return reportService.getReportData( reportName );
            }]
        },
          controller: 'reportRoutingCtrl'
    });
}]);
app.controller('reportRoutingCtrl', ['$scope', 'reportData', 'reportName', function( scope, reportData ) {

    console.log( reportName );
    console.log( reportData );

}]);

再一次,你约瑟夫!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-29
    • 2017-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多