我刚刚在我的 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/