ъглово натоварване локален json файл чрез услуги

Опитвам се да заредя локален json файл в същата директория като сервизния ми файл.

Няма JS грешки и под раздела Net виждам, че json файлът е зареден.

И все пак настройването на отговора txt на променливата "static_obj" не зарежда JSON данни. Когато имам JSON данни, твърдо кодирана var WEBTEST = {}, тя се зарежда добре. Защо?

'use strict';

webTestApp.factory('webtest', function ($q, $timeout) {
var Webtest = {
    //Methods exposed for the class
    fetch: function(callback){
        //fetch the data from below hard coded
        var deferred = $q.defer();        
        var static_obj = [];
        var promised = deferred.promise;
        var xobj = new XMLHttpRequest();

        //giving an artificial delay of .03 seconds..
        //controller will render the page & will show the service data after .03 seconds
        $timeout(function(){
            xobj.overrideMimeType("application/json");
            xobj.open('GET', 'angular/scripts/services/webtest.json', true);
            xobj.onreadystatechange = function () {
                if (xobj.readyState == 4 && xobj.status == "200") {
                    static_obj = $.parseJSON(xobj.responseText);
                }
            };
            xobj.send(null);
            promised.then(callback(static_obj))
        }, 30);

        return promised;
    }
}

return Webtest;
});

Следният код работи добре, но искам да мога да зареждам json файлове, вместо да кодирам твърдо JSON.

'use strict';

webTestApp.factory('webtest', function ($q, $timeout) {
var Webtest = {
    //Methods exposed for the class
    fetch: function(callback){
        //fetch the data from below hard coded
        var deferred = $q.defer();        
        var static_obj = null;
        var promised = deferred.promise;

        //giving an artificial delay of .03 seconds..
        //controller will render the page & will show the service data after .03 seconds
        $timeout(function(){
            static_obj = WEBTEST;
            promised.then(callback(static_obj))
        }, 30);

        return promised;
    }
}

return Webtest;
});

var WEBTEST = [
{"id": "0","Name": "Items 0", "Description": "Description 0"},
{"id": "1","Name": "Items 1", "Description": "Description 1"},
{"id": "2","Name": "Items 2", "Description": "Description 2"},
{"id": "3","Name": "Items 3", "Description": "Description 3"},
{"id": "4","Name": "Items 4", "Description": "Description 4"},
{"id": "5","Name": "Items 5", "Description": "Description 5"},
{"id": "6","Name": "Items 6", "Description": "Description 6"},
{"id": "7","Name": "Items 7", "Description": "Description 7"},
{"id": "8","Name": "Items 8", "Description": "Description 8"},
{"id": "9","Name": "Items 9", "Description": "Description 9"},
{"id": "10","Name": "Items 10", "Description": "Description 10"},
{"id": "11","Name": "Items 11", "Description": "Description 11"},
{"id": "12","Name": "Items 12", "Description": "Description 12"},
{"id": "13","Name": "Items 13", "Description": "Description 13"},
{"id": "14","Name": "Items 14", "Description": "Description 14"},
{"id": "15","Name": "Items 15", "Description": "Description 15"},
{"id": "16","Name": "Items 16", "Description": "Description 16"},
{"id": "17","Name": "Items 17", "Description": "Description 17"},
{"id": "18","Name": "Items 18", "Description": "Description 18"},
{"id": "19","Name": "Items 19", "Description": "Description 19"},
{"id": "20","Name": "Items 20", "Description": "Description 20"},
{"id": "21","Name": "Items 21", "Description": "Description 21"},
{"id": "22","Name": "Items 22", "Description": "Description 22"},
{"id": "23","Name": "Items 23", "Description": "Description 23"},
{"id": "24","Name": "Items 24", "Description": "Description 24"},
{"id": "25","Name": "Items 25", "Description": "Description 25"},
{"id": "26","Name": "Items 26", "Description": "Description 26"},
{"id": "27","Name": "Items 27", "Description": "Description 27"},
{"id": "28","Name": "Items 28", "Description": "Description 28"},
{"id": "29","Name": "Items 29", "Description": "Description 29"},
{"id": "30","Name": "Items 30", "Description": "Description 30"},
{"id": "31","Name": "Items 31", "Description": "Description 31"},
{"id": "32","Name": "Items 32", "Description": "Description 32"},
{"id": "33","Name": "Items 33", "Description": "Description 33"},
{"id": "34","Name": "Items 34", "Description": "Description 34"},
{"id": "35","Name": "Items 35", "Description": "Description 35"},
{"id": "36","Name": "Items 36", "Description": "Description 36"},
{"id": "37","Name": "Items 37", "Description": "Description 37"},
{"id": "38","Name": "Items 38", "Description": "Description 38"},
{"id": "39","Name": "Items 39", "Description": "Description 39"},
{"id": "40","Name": "Items 40", "Description": "Description 40"},
{"id": "41","Name": "Items 41", "Description": "Description 41"},
{"id": "42","Name": "Items 42", "Description": "Description 42"},
{"id": "43","Name": "Items 43", "Description": "Description 43"},
{"id": "44","Name": "Items 44", "Description": "Description 44"},
{"id": "45","Name": "Items 45", "Description": "Description 45"}
];

person kronus    schedule 25.02.2014    source източник


Отговори (1)


Има ли причина да не използвате услугата build in $http за извличане на JSON? С него може да бъде по-просто:

webTestApp.factory('webtest', function($timeout, $http) {
    var Webtest = {
        fetch: function() {
            return $timeout(function() {
                return $http.get('webtest.json').then(function(response) {
                    return response.data;
                });
            }, 30);
        }
    }

    return Webtest;
});

и в контролера:

webtest.fetch().then(function(data) {
    $scope.data = data;
});

Ето фиксиран код:

http://plnkr.co/edit/f1HoHBGgv9dNO7D7UfPJ?p=preview

Както и да е, вашият проблем беше, че върнахте обещание, но никога не го разрешихте (deferred.resolve). в този ред

promised.then(callback(static_obj))

не разрешавате обещание, а ръчно извиквате callback с някои данни. Работи, защото в случай на твърдо кодиран json обект той вече е наличен в страницата, но в случай на ajax заявка се опитахте да го извикате, преди да дойде отговорът. Така че ще трябва да преместите promised.then(callback(static_obj)) във функция onreadystatechange. Но ако тръгнете по този начин, изобщо не се нуждаете от отложено и обещание, просто използвате обратно извикване.

person dfsq    schedule 25.02.2014
comment
Току-що опитах вашия код, но той прави същото като това, което правеше моят код. Все още не виждам данните да се попълват. Също така съм настроил контролера по начина, по който го имате по-горе, но вашият код е по-ефективен - person kronus; 25.02.2014
comment
Сравнете моя пример от работещ plunker с вашия код, трябва да има проста грешка. - person dfsq; 25.02.2014
comment
Виждам, че вашият код работи в pinkr. Има ли начин да кача zip файл на моя проект. Може би проблемът е в изгледите. Също така се опитвам да пагинирам страници и да огранича само до 15 елемента на раздел - person kronus; 25.02.2014
comment
Бяхте правилен, обещаното.then(callback(static_obj)) трябваше да бъде в рамките на функцията onreadystatechange. Благодаря ти. Следващата фаза е да разбера как да направя това динамично за извикване на всеки json файл, който желая. Благодаря ви, благодаря ви, благодаря ви - person kronus; 25.02.2014