javascriptangularjsangular-promiseangularjs-factoryangularjs-http

Unable to fetch json data using angular factory service


I am unable to fetch my json data using angular factory service. I seem to load the files correctly, no error on developer tools console, still the data is undefined on the request - means empty.

My json file:

{
  "Translations": [
    {
      "WhatsNew": [
        {
          "English": "Whats New",
          "Hebrew": "מה חדש?",
          "Arabic": "الجديد في الموقع"
        }

      ],
      "SearchByWord": [
        {
          "English": "Search By Word",
          "Hebrew": "חיפוש לפי ערך",
          "Arabic": "البحث حسب الكلمة"
        }
      ],
      "SearchByRoot": [
        {
          "English": "Search By Root",
          "Hebrew": "חיפוש לפי שורש",
          "Arabic": "البحث حسب الجذر"
        }
      ],
      "HebrewArabicIndex": [
        {
          "English": "to the Hebrew-Arabic Index",
          "Hebrew": "לאינדקס העברי-ערבי",
          "Arabic": "إلى الفهرس العبري- العربي"
        }
      ],
      "ArabicHebrewDictionary": [
        {
          "English": "to the Arabic-Hebrew Dictionary",
          "Hebrew": "למילון הערבי-עברי",
          "Arabic": "إلى القاموس العربي- العبري"
        }
      ],
      "ExamplesAndNotes": [
        {
          "English": "Examples and Notes",
          "Hebrew": "דוגמאות והערות",
          "Arabic": "أمثلة    وملاحظات"
        }
      ],
      "IdiomsAndExpressions": [
        {
          "English": "Idioms and Expressions",
          "Hebrew": "ביטויים וצירופים",
          "Arabic": "تعابير لغوية"
        }
      ],
      "WordsFromSameRoot": [
        {
          "English": "Words From Same Root",
          "Hebrew": "ערכים מאותו השורש",
          "Arabic": "مشتقات الجذر"
        }
      ],
         "SearchResults": [
        {
          "English": "Search Results",
          "Hebrew": "תוצאות החיפוש",
          "Arabic": "نتائج البحث"
        }
      ]
    }
  ]
}

JS file:

adicApp.factory('langService', function ($http) {
    return {
        getLanguage: getLanguage,
        setLanguage: setLanguage,
        getLangRes: getLangRes
    };

    var _lang;
    function getLanguage() {
        return _lang;
    }
    function setLanguage(lang) {
        _lang = lang;
    }

    function getLangRes(lang) {
        var langRes;

        _lang = lang;

        switch (lang) {
            case "English":
                langRes = getEnglishLangRes();
                break;

            case "Hebrew":
                langRes = getHebrewLangRes();
                break;

            case "Arabic":
                langRes = getArabicLangRes();
                break;

            default:
                langRes = getEnglishLangRes();
                break;
        }

        return langRes;
    }

    function getEnglishLangRes() {
        var res = [];
            //{
            //    Partial1_Key: "Partial 1",
            //    Partial2_Key: "Partial 2",
            //    Search_String_Value_Key: "Search String Value",
            //    Count_Of_Words_Key: "Count Of Words",
            //    Data_Id_Key: "Data ID",
            //    Value_Key: "Value",
            //    Search_Category_Key: "Search Category",
            //    Whats_New: null
            //};
        $http.get('../Scripts/Languages/languages.json').success(function (data) {
              res = data.translations
        })
        .error(function (data, status, headers, config) {
            alert("Status: " + status);
            //$log.error('Problem on selectCountry api Cities :' + status);
        });

        return res;
    }

    function getHebrewLangRes() {
        var res =
            {
                Partial1_Key: "חֵלֶק 1",
                Partial2_Key: "חֵלֶק 2",
                Search_String_Value_Key: "ערך מחרוזת חיפוש",
                Count_Of_Words_Key: "ספירת מילים",
                Data_Id_Key: "מספר מזהה",
                Value_Key: "ערך",
                Search_Category_Key: "חיפוש קטגוריה"
            };

        return res;
    }

    function getArabicLangRes() {
        var res =
            {
                Partial1_Key: "الجزء 1",
                Partial2_Key: "الجزء 2",
                Search_String_Value_Key: "قيمة سلسلة البحث",
                Count_Of_Words_Key: "عدد الكلمات",
                Data_Id_Key: "رقم الهوية",
                Value_Key: "القيمة",
                Search_Category_Key: "فئة البحث"
            };

        return res;
    }
});

And view:

 <div class="hidden-xxs hidden-xs hidden-sm col-md-3 col-lg-4">
            <div id="scrolling-news-sidebar" class="sidebar">
                <h2>{{langRes.WhatsNew[0]}}</h2>
                <div class="marquee">

Any idea as to why it is not working? I am at a loss. I tried looking through the web for an answer, non seemed to help so far. I thought there is a problem with my json but I can find no suspicious things about my file.


Solution

  • To start, return your promises:

    function getEnglishLangRes() {
        var res = [];
            //{
            //    Partial1_Key: "Partial 1",
            //    Partial2_Key: "Partial 2",
            //    Search_String_Value_Key: "Search String Value",
            //    Count_Of_Words_Key: "Count Of Words",
            //    Data_Id_Key: "Data ID",
            //    Value_Key: "Value",
            //    Search_Category_Key: "Search Category",
            //    Whats_New: null
            //};
         ͟r͟e͟t͟u͟r͟n͟ $http.get('../Scripts/Languages/languages.json')
          ̶.̶s̶u̶c̶c̶e̶s̶s̶ .then(function (response) {
              var data = response.data
              res = data.translations
              ͟r͟e͟t͟u͟r͟n͟  res; 
        })
          ̶.̶e̶r̶r̶o̶r̶ .catch(function (response) {
            var status = response.status;
            alert("Status: " + status);
            //$log.error('Problem on selectCountry api Cities :' + status);
            //IMPORTANT
            throw response;
        });
    
        ̶r̶e̶t̶u̶r̶n̶ ̶r̶e̶s̶;̶
    }
    

    When a .catch method response handler omits a throw statement it converts a rejected promise to a fulfilled promise.