如何在没有持续服务器请求的情况下在 AngularJS 中进行视图重定向

How to make View redirects in AngularJS without constant server requests

本文关键字:AngularJS 情况下 重定向 视图 请求 服务器      更新时间:2023-09-26
每次

当我进行View重定向时(我使用 href 这样做),我可以看到 AngularJS 运行GetAjaxData1GetAjaxData2。换句话说:我每次进行重定向时都会这样做,而不是对服务器的单个初始请求View请求。怎么了?

这是我的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();
};

您绝对必须阅读有关$http和ng资源库的信息,并且 在您的应用程序中尝试更多角度的方式,您也应该 了解 AJAX 请求始终是异步的,并尝试 了解承诺模式。

从技术上讲 - 你需要的是缓存 - 无论你如何实现这一点 - 你都需要对 API 和 to cache 变量进行一次调用。

我不喜欢使用 $.ajax 的想法,但它看起来像这样:

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

控制器不是单例。因此,每次您的视图更改时都会创建您的"UController"。我假设工厂是在这个控制器内部使用的。请参阅:AngularJS控制器的生命周期是什么?