Taehun Ahn Taehun Ahn - 3 months ago 17
HTML Question

Wait until all the data is loaded . AngularJS

I am writing a code that would call DATA from JASON file.
I had an asynchronous problem and saw many posts about same issue.

I wrote some code that I guess it would fix my problem.
It, however, seems like the data is still not loaded.

I will be more specific with my question. I used promise method below. I thought 'questions' should not be returned before all the data is fully loaded. Apparently, 'questions', having nothing inside, is returned to my page.

Is my promise method correct? if not how can I fix this problem.
Can someone please help me?

(function(){

angular
.module("GrammarQuiz")
.factory("DataService", DataFactory);
function DataFactory($log, $q, $http, $timeout){
var vm = this
var questions = getData() ;
vm.getData = getData;

function getData(){
var defer = $q.defer()
$http.get('api/data1.json')
.success(function(res){
questions = res;
$log.log('success');
defer.resolve(res);
})
.error(function(err, status){
$log.log('fail');
defer.reject(err);
})
return defer.promise;
}


$log.log('check');
$log.log(questions[0]);

return questions;
}


})();

Lex Lex
Answer

What you have shown is not the proper way to use Promises. Instead you should be doing something similar to the following:

Factory (Service)

.factory("DataService", DataFactory);

function DataFactory($http) {
    var service = {};
    service.getData = function () {
        return $http.get('api/data1.json')
            .then(function(response) {
                return response.data;
            });
        };
    return service;
}

Controller

.controller("MyController", MyController);

function MyController($scope, DataService) {
    $scope.questions = {}; // or $scope.questions = []; if the return type is an array
    DataService.getData()
        .then(function(data) {
            $scope.questions = data;
        })
        .catch(function(errorResponse) {
            // do something with the error
        });
}