0

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.

georgeawg
  • 48,608
  • 13
  • 72
  • 95
Barr J
  • 10,636
  • 1
  • 28
  • 46
  • This is very confusing. You have functions to retrieve each language independently, yet the same JSON has the language strings under an array based on the English equivalent. I feel like something is missing in the code to have `res` equate to what you've type under Hebrew/Arabic. That said, you are loading a JSON file with an object having **T**ranslations as the property, but your `$http` method is looking for **t**ranslations (lower-case). – Brian Aug 13 '17 at 12:30
  • When asking a question about a problem caused by your code, you will get much better answers if you provide code people can use to reproduce the problem. That code should be… **Minimal** – Use as little code as possible that still produces the same problem. See [How to create a Minimal, Complete, and Verifiable example](https://stackoverflow.com/help/mcve). – georgeawg Aug 13 '17 at 13:46

2 Answers2

1

The $http request success and failure callbacks are no more coming as "success" or "error" as a curry function. They are based on Promises concept. So there will be a "then" curry function which will have both success and error inside its control block.

The format you have used is supported in AngularJS 1.4 Library. So please check first what version of Angular you are using.

If you are using latest AngularJS 1.6 library then format your request as below -

$http.get('data.json').then(function success(data) {
      console.log(data)
}, function error(res){
      console.log(res);
});

I have checked this in Plunker and it is working fine. https://embed.plnkr.co/eoLHfd3gzbTLAXdnNVXi/

Ashvin777
  • 1,446
  • 13
  • 19
  • I am using below. I have switched from $http.get to $http.jsonp however there is a syntax error: unexpected token at ':' at line 2 in the json – Barr J Aug 13 '17 at 12:33
  • Use $http.get and try – Ashvin777 Aug 13 '17 at 12:34
  • tried to no avail, $http.get returns null – Barr J Aug 13 '17 at 12:38
  • Sorry I am not able to understand what you mean here. May I know the AngularJS Library version you are using. Also is it possible for you to create a Plunker and showcase the problem to me – Ashvin777 Aug 13 '17 at 12:40
1

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.

georgeawg
  • 48,608
  • 13
  • 72
  • 95