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 ;-) 
 
    } 
 
};

相关问题