更新時間:
這個問題可以很容易地通過使用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
可以增加服務超時按您的要求; – Rahul
爲什麼你要延遲..我相信你的測試函數會在頁面加載時立即調用! – Rahul
添加任意'$ timeout'延遲是應對異步代碼的一種可怕方式。使用已解決的Promise來控制何時運行代碼依賴於AJAX調用,或者設計組件,以便在Ajax調用仍在進行時能夠處理空數據。 –