简体   繁体   English

AngularJS路由和Ajax数据有关路由更改

[英]AngularJS routes and Ajax data on route change

I am failing to understand the Angular way to do the following... 我无法理解执行以下操作的Angular方法...

I have a router configured, once the route is changed, and the templateUrl is supplied I would like to make an Ajax call to fetch some JSON data. 我配置了路由器,更改路由后,提供了templateUrl,我想进行Ajax调用以获取一些JSON数据。

Notice that, i do not want to wait to fetch the template and than use the controller to fetch the JSON data because that is two serial HTTP calls. 请注意,我不想等待获取模板,而不想使用控制器来获取JSON数据,因为这是两个串行HTTP调用。 I want to fetch the JSON data in parallel with fetching the template. 我想在获取模板的同时获取JSON数据。 Is there a well known pattern to do this? 有众所周知的模式可以做到这一点吗?

Correct me if I am wrong... For now, I understand that I should use the resolver in which I would call an a "data provider", which will fire an HTTP call to get the JSON data. 如果我错了,请纠正我...现在,我了解我应该使用解析器,在该解析器中我将调用一个“数据提供程序”,它将触发HTTP调用以获取JSON数据。 This data than will be available to the controller. 此数据将可供控制器使用。 So something like this... 像这样

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

Is this the correct pattern to follow? 这是正确的模式吗? If so, how can I get access to the 'urlData' object in the resolver? 如果是这样,我如何访问解析器中的“ urlData”对象?

Thank you for the help!! 感谢您的帮助!!

This is how I would do it (and what I think that it's the most accepted way to do it). 这就是我的做法(也是我认为这是最常用的方法)。

Imagine that you are rendering a view where the user can visualize one concrete item, and that you have to fetch the data from that item from the server. 想象一下,您正在渲染一个视图,用户可以在其中查看一个具体项目,而您必须从服务器从该项目中获取数据。

I would have a service like this one: 我会得到这样的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;
  };
}]);

My routeProvider would look like this: 我的routeProvider看起来像这样:

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

And the signature of the controller would be like this: 控制器的签名将如下所示:

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

Notice that the resolve will be injecting the fetched item into the controller. 请注意,解决方案将把获取的item注入到控制器中。

To summarize what's been offered by Josep and to put it into one final solution, here is the code in case anyone else was wondering about the same... 总结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 );

}]);

Once again that you Josep! 再一次,你约瑟夫!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM