2 $ http получить функцию - PullRequest
0 голосов
/ 09 мая 2018

Учитывая 2 JSON URL, как мне убедиться, что код завершил извлечение данных из a.json, затем только начать извлекать данные из b.json, а затем только запустить функцию init?

var aUrl = "a.json";
var bUrl = "b.json"; 

Моя попытка:

var app = angular.module('calendarApp', []);
app.controller('ctrl', function($scope, $http) { 
  $http.get(aUrl).success(function(data) {   }); 
  $http.get(bUrl).success(function(data) {  
   init()}
);
var init = function(){}

Ответы [ 5 ]

0 голосов
/ 09 мая 2018
I faced the same issue in my initial days.
There are many ways of doing it exactly as suggested here.
You need to know below two things before exploring:

1. JavaScript синхронен

Synchronous Example[Flow in sequence]:
       console.log('1')
       console.log('2')
       console.log('3')

Журналы 1 2 3.

Пример совершения звонков в сервис

   1. $http.get(aUrl).success(function(data) {  console.log('1.any time response returns')  });  
   2. $http.get(bUrl).success(function(data) { console.log('2.mummy returns')};

Так как однопоточный javascript сначала вызовет ваш код ниже с помощью $ http.get (aUrl), который переходит по URL и обрабатывает данные из фона.

  1. $ http.get (aUrl) .success (function (data) {console.log ('1.any time response возвращает')});

Но главное, на что нужно обратить внимание, это то, что $ http.get (aUrl), запрошенный выше, не ждет, пока данные будут возвращены в случае успеха / ошибки. Он переходит к следующему запросу $ http.get (bUrl), и мы просто не можем предсказать, какой ответ придет раньше.

  1. $ http.get (bUrl) .success (function (data) {console.log ('2.mummy Return'))}

Вывод может быть либо

1. любой ответ времени возвращается

2. Мумия возвращается

                     or

2. Мумия возвращается

1. любой ответ времени возвращается

Итак, чтобы преодолеть эту ситуацию, мы выполняем асинхронные операции различными способами.

2. Асинхронные вызовы

$http.get(aUrl)
    .then(function(response){
      console.log('inside the first then response');
      console.log(response.data);

      //executing the second request after we get the first request
     //and returns the **outputResponse** which is captured in the next **then** block
      return $http.get(bUrl);
    })
    .then(function(**outputResponse** ){
      console.log('outputResponse generated from to the second bUrl');
      //you can call init() here 
    });

Выше кода достаточно для вашего требования.

Нажмите для получения дополнительной информации, используя $ q в будущем

Нажмите здесь, чтобы узнать, почему использовать вместо успеха.

0 голосов
/ 09 мая 2018

Предлагаю использовать обещания AngularJS. Преимущество заключается в одновременной загрузке данных асинхронно, без необходимости ждать завершения первого запроса. см .: https://docs.angularjs.org/api/ng/service/$q

var promises = [];

var loadingJson = function(url){
  var defer = $q.defer();

  $http.get(url).then(function(results){
    defer.resolve(results);
  }, function(err){
    defer.reject(err);
  });

  return defer.promise;
};

promise.push(loadingJson('example.com/1.json'));
promise.push(loadingJson('example.com/2.json'));

$q.all(promises).then(function(resultList){
  // Your hanadling here, resultList contains the results of both API calls.
}, function(errList){
  // Your error handling here.
});
0 голосов
/ 09 мая 2018

Вы можете создать сервисный слой, в котором определите два метода. Затем введите сервис в ваш контроллер:

//Controller
YourService.getUrl(urlA).then(function(response) {

            if(response != null && response.success == true){
                // do something
            }
            YourService.getUrl(urlB).then(function(response) {

                if(response != null && response.success == true){
                    // do something
                    init()
                }
            }, 
            function errorCallback(response) {

                console.log("Error YourService: getUrlB ---> ");
            }); 
        }, 
        function errorCallback(response) {
            console.log("Error YourService: getUrlA ---> ");
        });

// Example of method in your service    
this.getUrl = function(urlA) {
    try{
        var deferred = $q.defer();

        $http({
            method: 'GET',
            url: getUrlA,
            params: {},
            responseType: "json",
            cache: false
        })
        .success(function(data, status, headers, config) {

            deferred.resolve(data);
        })
        .error(function(data, status, headers, config) {

            deferred.reject(data);
        });

        return deferred.promise;
    }catch(e){
        /* */
        console.log("Service: getUrl ---> " + e);
    }
}
0 голосов
/ 09 мая 2018

$ http.get возвращает обещание, поэтому вы можете сделать:

return $http.get(aUrl)
    .then(function(result) {
        return $http.get(bUrl);
    })
    .then(function(result) {
        return init();
    },
    function (error) {
        // do something with the error
    });
0 голосов
/ 09 мая 2018

Возможно, это не лучший и не самый чистый метод, но быстро заставляющий ваш код делать то, что вы хотите, я получил:

var app = angular.module('calendarApp', []);
app.controller('ctrl', function($scope, $http) { 
  $http.get(aUrl).success(function(data) {   
      $http.get(bUrl).success(function(data) {  
         init()
      }
  }); 
);
var init = function(){}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...