簡體   English   中英

多次調用onInit掛鈎時,如何僅在Angular 1.5中調用一次特定的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$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(...) ,因此對API的調用只會在第一次調用TimesService.getTimes進行一次(因為結果將存儲在timesResult內部的timesResult )。

callInProgress和resultsLoaded在onInit函數內,並且是指令控制器的一部分。 每次使用指令時,它們都會被創建。 使用包含控制器上的controller屬性來執行類似的操作。 您可以使用綁定來指定控制器屬性,以使其保持某種通用性。

暫無
暫無

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

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