如何在 Angular 1.5 多次调用 onInit hook 时只调用一次特定的 promise

How to call a specific promise only once in Angular 1.5 when onInit hook is called multiple times

我正在对 onInit 函数进行 API 调用。

   vm.$onInit = function() {
        var callInProgress = false;
        var resultsLoaded = false;

        var url = '/api/times/cst';
        if(callInProgress === false && resultsLoaded ===false){
            callInProgress = true;
            HttpWrapper.send(url,{"operation":'GET'}).then(function(result){
                vm.times = result;
                resultsLoaded = true;
                },function(error){
                vm.errorInApi = true;
            });
        }

现在 $onInit 被多次调用,因此每次都会初始化两个标志 callInProgress, resultsLoaded

所以,检查有点不起作用。

每次调用 $onInit 时都会调用 API,初始化时多次调用。

如何才能只拨打一次电话? 不过,它已在 $onInit 上被调用。

callInProgress 和 resultsLoaded 在 onInit 函数中,是指令控制器的一部分。每次使用该指令时都会创建它们。在包含控制器上使用控制器 属性 来做类似的事情是可行的方法。您可以使用绑定来指定控制器 属性 您需要保持这种通用性。

我建议将 API 调用包装在服务中,例如:

(function (angular) {
    'use strict';

    angular
        .module('services.common')
        .service('TimesService', TimesService);

    TimesService.$inject = ['HttpWrapper'];

    function TimesService(HttpWrapper) {
        var timesService = this;
        var timesResult = null;

        timesService.getTimes = getTimes;

        function getTimes() {
            if (!timesResult) {
                timesResult = HttpWrapper.send('/api/times/cst', {"operation": 'GET'});
            }
            return timesResult;
        }

        return timesService;
    }

})(angular);

然后将其注入到您的控制器中并像 TimesService.getTimes().then(...) 一样使用将存储在服务内的 timesResult 中。