繁体   English   中英

$ http用角度路由调用

[英]$http calls with angular routes

我只是在我的角度应用程序中设置路线。 第一个视图, 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是构建我的列表的原因。

您想要的是一项服务,它在角度上是一个单例:

.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 + '"');
  });
}

暂无
暂无

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

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