2017-08-10 171 views
1

我想在angularjs中添加一些延遲。以便它可以從api獲取數據。因爲我的api很重。我正在調用這個函數。基本上我想要一些延遲加載頁面,以便我的API工作正常。我嘗試了一些時間,我的數據立即出現一些錯誤。當我刷新我的網頁時,它工作正常。在angularjs中添加延遲

 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

可以增加服務超時按您的要求; – Rahul

+0

爲什麼你要延遲..我相信你的測試函數會在頁面加載時立即調用! – Rahul

+1

添加任意'$ timeout'延遲是應對異步代碼的一種可怕方式。使用已解決的Promise來控制何時運行代碼依賴於AJAX調用,或者設計組件,以便在Ajax調用仍在進行時能夠處理空數據。 –

回答

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

+0

我想延遲每一個呼叫(終端)?當他們被叫。 –

+0

如果您有$ http請求,它使用承諾等待接收數據,因此不需要設置延遲,您是否在應用程序中使用任何角度路由器(ui-router)?我給出的這一行將增加HTTP請求的等待時間,我給出這個是因爲我認爲請求超時。 –

+0

@DeveshKhosla angular有一個$ routeprovider服務,在那裏你可以把你的http請求放在一個解析參數中,直到http請求完成纔會加載頁面。 http://embed.plnkr.co/kHXK54也是http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx –