我想在angularjs中添加一些延迟。这样它就可以从api中获取数据。因为我的api很重。我叫这个功能。基本上我想要加载页面一些延迟,以便我的api正常工作。我试了一段时间,我的数据立刻拉了一段时间我收到错误。当我刷新我的页面时,它工作正常。
Help to put $timeout function in this angularjs
// Geting test stuff
$scope.teststuff = function () {
$scope.loading = true;
$http.get(settings.WebApiBaseUrl + 'Api/testing')
.success(function (data) {
$scope.mydata = data;
$scope.loading = false;
}).error(function (data, status, headers, config) {
alert("Error " + status )
$scope.loading = false;
})
}
答案 0 :(得分:0)
<强>更新强>
使用resolve property of $routerProvider
可以轻松解决此问题。请使用此配置。所以这里路由/ed
在解析完成之前不会加载,这意味着http请求必须返回一个值,只有在页面加载之后才会返回。
app.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
var settings.WebApiBaseUrl = "some url you want to use";
$routeProvider.when("/al", { templateUrl: "Views/test.html", controller: "testCtrl" })
.when("/ed", {
templateUrl: "Views/test2.html",
controller: "test2Ctrl",
resolve: {
initialize: function($http, $sessionStorage){
$http.get('api/ApiKey/' + $sessionStorage.user)
.success(function (myKey) {
return $http.get(settings.WebApiBaseUrl + 'Api/test1', { headers: { 'X-ApiKey': myKey } })
.success(function (data) {
return data;
}).error(function (data, status, headers, config) {
alert("error" + status);
});
}).error(function (data, status, headers, config) {
alert("error" + status);
});
}
}
})
.otherwise({
redirectTo: '/al'
});
}]);
现在你需要做控制器。
app.controller( 'test2Ctrl', function ( $scope, initialize ) {
$scope.loading=false;
$scope.test1=initialize;
$scope.loading=true;
});
旧答案: 所以你有一个http请求,这是一个承诺,并会等到收到数据,从你的例子我可以看到你正在实现一个加载屏幕的东西,直到http请求完成。
为确保笨重的http请求不会超时,您可以使用。
angular.module('MyApp', [])
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.timeout = 5000;
}]);
当页面等待http请求完成时,您可以使用范围变量($scope.loading = true;
)激活加载微调器库来屏蔽页面。结帐angular loading overlay或其他一些代码来执行此操作。
参考: http timeout