Angular asynchronous ng-repeat

Asked

Viewed 145 times

0

I am using Angular 1.6.10 to show the data of an API, as the data search is asynchronous, I believe ng-repeat runs before the data is loaded:

angular
  .module('appDataPOA', [])
  .controller('controllerDataPOA', async function() {
    this.data = await getDataPOA();
    console.log(this.data); //Retorna o array de objetos corretamente
  });

async function getDataPOA() {
  if (navigator.onLine) {
    let json = [];

    for (let resource of ['c003f659-dc05-4e64-8a5a-0f730ac8cff2', 'c2da9ff7-94c8-43af-8141-d03f8d325739', '9b019d7c-1956-4cf8-bc75-9041284d5d81']) {
      json = json.concat(
        await fetch(`http://datapoa.com.br/api/action/datastore_search?resource_id=${resource}&limit=500`)
        .then(data => data.json())
        .then(dataJSON => dataJSON.result.records)
        .catch(error => error)
      );
    }

    localStorage.dataPOA = JSON.stringify(json);

    return json;
  } else if (localStorage.dataPOA) {
    return JSON.parse(localStorage.dataPOA);
  } else {
    return null;
  }
}
<html lang="pt-BR" ng-app="appDataPOA">

<body ng-controller="controllerDataPOA as control">
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.10/angular.min.js"></script>

  <h1>{{control.data.length}} universidades, faculdades, escolas estaduais e federais cadastradas</h1>
  <table>
    <thead>
      <tr>
        <th>Nome</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="row in control.data">
        <td>{{row.NOME}}</td>
      </tr>
    </tbody>
  </table>
</body>

</html>

getDataPOA is a function that takes the data from the API (actually 3 and joins everything together)

  • 1

    acredito que o ng-repeat é executado antes dos dados serem carregados This is incorrect. ng-repeat runs throughout the life of the page. A question, after the requests in the Apis, you made a console.log() to make sure that the data were actually captured? It may be that they were not captured, so there is nothing to show.

  • Fez is in the code I posted, so what’s the problem?

  • You made a console.log() just after the function call, I thought I’d put them on each then of your code, to make sure it’s all right.

  • Could you explain it better? I don’t understand why, what good will it do?

  • Using a.log console you can get an idea of what the hell is going on in the instruction sequence you’re passing to javascript. Let’s say that your code should be working, but during the requests it receives a null object of response and then the thing starts to go wrong?

1 answer

0


Angular has its own implementation for API consumption, the $http:

angular.module('httpExample', [])
.controller('FetchController', ['$scope', '$http', '$templateCache',
  function($scope, $http, $templateCache) {
    $scope.method = 'GET';
    $scope.url = 'example.com';

    $scope.fetch = function() {
      $scope.code = null;
      $scope.response = null;

      $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
        then(function(response) {
          $scope.status = response.status;
          $scope.data = response.data;
        }, function(response) {
          $scope.data = response.data || 'Request failed';
          $scope.status = response.status;
      });
    };
  }
]);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.