簡體   English   中英

用幾個Ajax請求初始化控制器的最佳方法

[英]Best way to initialize a controller with several ajax requests

我有2個使用ng-init調用的$http函數,因為它們返回的數據填充了頁面。

ng-init = "getOpen(); getClosed();"

這是最好的方法嗎?

第一功能;

$scope.getOpen = function () {
    $http({
        method: 'post',
        url: "http://www.example.co.uk/php/open-get.php",
        data: $.param({ 'location' : $scope.l, 
                       'time' : $scope.t,
                       'day' : $scope.d,
                       'type' : 'get_restopen' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).
    success (function(data, status, headers, config){
        if(data.success && !angular.isUndefined(data.data) ){
            $scope.open = data.data;
        } else {
            $scope.open = [];
        }
    }).
    error(function(data, status, headers, config) {
        //$scope.messageFailure(data.message);
    });
}

第二功能;

$scope.getClosed = function () {
    $http({
        method: 'post',
        url: "http://www.example.co.uk/php/closed-get.php",
        data: $.param({ 'location' : $scope.l, 
                       'time' : $scope.t,
                       'day' : $scope.d,
                       'type' : 'get_restopen' }),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).
    success (function(data, status, headers, config){
        if(data.success && !angular.isUndefined(data.data) ){
            $scope.closed = data.data;
        } else {
            $scope.closed = [];
        }
    }).
    error(function(data, status, headers, config) {
        //$scope.messageFailure(data.message);
    });
}

一切正常。 我的問題是在AngularJS中這是一種有效的處理方式嗎? 我是新手,所以只想尋求指導。

1-我的$http是否同時執行? 還是在另一個開始之前就完成了?

2-是否需要在我的代碼中引入$qpromises 這些功能彼此獨立

3-如何檢測所有$http請求何時完成,而不管是否成功

以下代碼正確嗎?

$q.all([$scope.getOpen, $scope.getClosed]).then(function() {
     //Both requests have been completed and I shall now set a bolean
     $scope.compelete = true;
});
  1. 假設您自己在某個地方調用了這兩種方法,是的。 $http調用默認是異步的

  2. 已經完成, $http實際上會返回一個承諾!

  3. promise.all()是一種無需修改promise回報的優雅方法。 它實際上是完成監視程序。 有關承諾參考的更多詳細信息

$ http是異步的,因此您的2個調用應並行執行。 如果您確實需要將這兩個函數簡化為一個,和/或需要檢查所有$ http請求是否已完成,則可以使用$ q.all Angularjs $ q.all

我有2個使用ng-init調用的$ http函數,因為它們返回的數據填充了頁面。

ng-init =“ getOpen(); getClosed();”

這是最好的方法嗎?

正如角度文檔中所說:

可以濫用此指令在模板中添加不必要的邏輯量。 ngInit只有少數適​​當的用法,例如別名ngRepeat的特殊屬性,如下面的演示所示; 以及通過服務器端腳本注入數據。 除了這幾種情況,您應該使用控制器而不是ngInit來初始化作用域上的值。

您可以在這里找到它: https : //docs.angularjs.org/api/ng/directive/ngInit

您應該避免在模板中使用ng-init。 在控制器中啟動某些東西的建議用法是直接在控制器內部調用私有函數。

我還建議閱讀有關angular的樣式指南:
https://github.com/johnpapa/angular-styleguide

1-我的$ http是否同時執行? 還是在另一個開始之前就完成了?

這兩個呼叫幾乎同時開始。 然后,javascript擁有一堆他從服務器獲取答案時必須執行的回調。 只需在瀏覽器中按F12鍵,然后找到“網絡”標簽即可查看所有正在啟動的請求。

此外,現在不建議使用“ .success”。 您應該使用“ .then” https://docs.angularjs.org/api/ng/service/$http#deprecation-notice

2-是否需要在我的代碼中引入$ q或promises? 這些功能彼此獨立

在這種情況下不行。 如果您想在兩個調用都執行后執行某項$q.all([promise1, promise2])可以使用$q.all([promise1, promise2])

3-如何檢測所有$ http請求何時完成,而不管是否成功

看看$ httpInterceptors。 讓您分享我實現的一段代碼

angular.module("myModule").factory("myHttpInterceptor", [
    "LoadingService",
    "$q",
    "Alert",
    function (LoadingService, $q, Alert) {

        function requestInterceptor(config) {
            LoadingService.increaseCounter();
            return config;
        }

        function responseInterceptor(response) {
            LoadingService.decreaseCounter();
            return response;
        }
   // ...

以下代碼正確嗎?

 $q.all([$scope.getOpen, $scope.getClosed]).then(function() { //Both requests have been completed and I shall now set a bolean $scope.compelete = true; }); 

不,因為您仍然希望函數可以返回它。 另外,“。success”不會實現承諾鏈。 您現在必須使用´.then()´

$scope.getOpen = function () {
    return $http({
        // config
    }).
    then(function(data, status, headers, config){
        //handling success
    },(function(data, status, headers, config) {
        //handling error
    });

總結:

angular.module("yourApp").controller("someController", ["$scope", "$q"
    function($scope, $q){

        // init
        init();

        // Shared functions

        $scope.getOpen = function () {
          return $http({
             method: 'post',
             url: "http://www.example.co.uk/php/open-get.php",
             data: $.param({ 'location' : $scope.l, 
                   'time' : $scope.t,
                   'day' : $scope.d,
                   'type' : 'get_restopen' }),
             headers: {'Content-Type': 'application/x-www-form-urlencoded'}
          });

        $scope.getClosed = function () {
          return $http({
            // config
          });

        // private functions
        function init(){
             var promises = [];

             promises.push($scope.getOpen());
             promises.push($scope.getClosed());

             $q.all(promises).then(function(datas){
                  // Here, you know both calls have been successfull
                  // datas[0] is the result of $scope.open()
                  $scope.open = datas[0].data;
                  $scope.complete = true;

             }, function(errors){
                  $scope.complete = true;
                  // You fall here if one of your calls has failed
             });
        }

    }
]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM