javascript - 使用 Angular 路由的 $http 调用

标签 javascript angularjs

我刚刚在我的 Angular 应用程序中设置了路线。第一个 View 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 但这不起作用。 ListView 只是空白。 $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 + '"');
  });
}

关于javascript - 使用 Angular 路由的 $http 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15580692/

相关文章:

javascript - angularjs - 动态函数返回

javascript - Node JS。 TypeError : https. 请求不是函数

angularjs - Angular UI Bootstrap Modal 不适用于 ng-include

javascript - Node.js 数组实例化

javascript - jQuery 中的 Object.values()

javascript - JSON stringify 无法使用替换函数转义单引号

javascript - angularjs工厂内部函数不依赖于工厂吗?

javascript - ng-repeat 和过滤 Angular 基元数组

javascript - 如何在angular js中获取自定义属性的值

javascript - 既然 $.browser 已被弃用,我如何使用 jQuery 检测 IE 8?