使用angular路由调用$http

$http calls with angular routes

本文关键字:http 调用 路由 angular 使用      更新时间:2023-09-26

我只是在我的angular应用程序中设置路由。第一个视图,List发出http调用来获取演示列表

function ListController($scope, $http)
{
    $scope.error            = null;
    $scope.presentations    = null;
    $scope.requesting       = true;
    $scope.currentTitle     = '-1';
    $data = {
        'type' : 'presentations'
    };
    $http.post('resources/request.php', $data, {timeout:20000})
        .success(function(data, status, headers, config)
        {
            $scope.requesting   = false;
            $scope.presentations    = data;
        })
        .error(function(data, status, headers, config)
        {
            $scope.requesting   = false;
            log(status + ', data:" ' + data + '"');
        }
      }
    );
}

我的路线是

angular.module('main',[]).
  config(function($routeProvider) {
    $routeProvider.
      when('/', {controller:ListController, templateUrl:'resources/views/list.html'}).
      when('/view/:id', {controller:VforumController, templateUrl:'resources/views/vforum.html'}).
      otherwise({redirectTo:'/'});
  });

我的问题是,当我去#/view/:id,然后回到/$http调用再次调用。如何才能使它只在第一次进入应用程序时加载并引用与第一次加载时相同的数据?

我尝试在angular外部创建一个变量,并将其设置为第一次加载的数据。然后,在ListController中基本上做了一个if data is null, do the $http call else set $scope.data = data,但那不起作用。列表视图是空白的。$scope.data是构建我的列表。

你想要的是一个服务,它在angular中是一个单例:

.factory( 'myDataService', function ( $http ) {
  var promise;
  return function ( $data ) {
    if ( ! angular.isDefined( promise ) ) {
      promise = $http.post('resources/request.php', $data, {timeout:20000});
    }
    return promise;
  }
});

现在您可以简单地将对$http的调用替换为对您的服务的调用:

function ListController( $scope, myDataService )
{
  // ...
  myDataService( $data ).then( function success( response ) {
    $scope.requesting = false;
    $scope.presentations = response.data;
  }, function error( response ) {
    $scope.requesting = false;
    log(status + ', data:" ' + response.data + '"');
  });
}