0

每當我使用View重定向時(我使用href來做到這一點),我可以看到AngularJS運行GetAjaxData1GetAjaxData2。換句話說:不是對服務器的單個初始請求,而是我每次做View重定向。哪裏不對?如何在沒有連續服務器請求的情況下在AngularJS中查看重定向

這裏是我的AngularJS代碼:

myApp.config(['$routeProvider', function ($routeProvider) { 
 
    $routeProvider.when('/', { 
 
     controller: 'UController', 
 
     templateUrl: '/Partial/View1.html' 
 
    }).when('/View2', { 
 
     controller: 'UController', 
 
     templateUrl: '/Partial/View2.html' 
 
    }).otherwise({redirectTo: '/View3'}); 
 
}]).factory('uFactory', function() { 
 
    var factory = {}; 
 
    data1 = []; 
 
    data2 = []; 
 

 
    factory.getAjaxData1 = function() { 
 
     $.ajax({ 
 
      url: url, 
 
      type: 'GET', 
 
      contentType: "application/json", 
 
      async: false, 
 
      success: function (result) { 
 
       data1 = result; 
 
      } 
 
     }); 
 

 
     return data1; 
 
    }; 
 

 
    factory.getAjaxData2 = function() { 
 
     $.ajax({ 
 
      url: url, 
 
      type: 'GET', 
 
      contentType: "application/json", 
 
      async: false, 
 
      success: function (result) { 
 
       data2 = result; 
 
      } 
 
     }); 
 

 
     return data2; 
 
    } 
 
}; 
 

 
var controllers = {}; 
 

 
controllers.uController = function ($scope, $location, uFactory) { 
 
    $scope.data1 = uFactory.getAjaxData1(); 
 
    $scope.data2 = uFactory.getAjaxData2(); 
 
};

+0

可能不應該使用'異步:FALSE'因爲它會鎖定在請求完成之前,UI還應該使用Angular的[$ http](https://docs.angularjs.org/api/ng/service/$http)服務,而不是jQuery的ajax –

回答

1

你一定要了解$httpng-resource庫和 嘗試更多角度的方式在你的應用程序,你也應該 明白,Ajax請求總是asynchronous,並嘗試 瞭解promise模式。

從技術上說 - 您需要的是緩存 - 無論您如何實現這一點,您都需要對API和緩存變量進行一次調用。

我不喜歡使用$阿賈克斯的想法,但它可以是這樣的:

angular.module('myApp').config(['$routeProvider', function ($routeProvider) { 
 
    $routeProvider.when('/', { 
 
     controller: 'UController', 
 
     templateUrl: '/Partial/View1.html' 
 
    }).when('/View2', { 
 
     controller: 'UController', 
 
     templateUrl: '/Partial/View2.html' 
 
    }).otherwise({redirectTo: '/View3'}); 
 
}]).factory('uFactory', function() { 
 
    return { 
 
     getFirstPromise: function() { 
 
      if (!this.$$firstPromise) { 
 
       this.$$firstPromise = $.ajax({ 
 
        url: url, 
 
        type: 'GET', 
 
        contentType: "application/json" 
 
       }).then(function (data) { 
 
        window.data1 = data; 
 
       }); 
 
      } 
 
      return this.$$firstPromise; 
 
     } 
 
     ... //some other code 
 
    } 
 
}); 
 

 
var controllers = { 
 
    uController: function ($scope, $location, uFactory) { 
 
     uFactory.getFirstPromise().then(function (data) { 
 
      $scope.data1 = data; 
 
     }); 
 
     // same for other data - and don't try to make ajax requests synhronous ;-) 
 
    } 
 
};

相關問題