0

Here are two demos of using AngularJS "$http.get().then(...)". One reads plain text files, and the other reads JSON files.

read plain text vs read JSON

However, the first one works but the second doesn't. Everything else is the same, except for file1.txt, file2.txt, file3.txt, and line 23 of app.js.

  /* content of file: 100 */

  function getNumber(file) {
      return $http.get(file).then(function(response){
         return parseInt(response.data, 10);
      });
  }

vs

  /* content of file: [{'n':100}] */

  function getNumber(file) {
      return $http.get(file).then(function(response){
         return response[0].n;
      });
  }

I followed this post by trying to create a service but still got some errors.

Basically, how to make the second one work? Thanks in advance! It would be more explicit if you look at the demos.

7
  • Perhaps response.data[0].n ? Commented Jun 10, 2015 at 20:48
  • No. that's not the problem. You can try it. @PSL Commented Jun 10, 2015 at 20:49
  • Which errors are you receiving from the 2nd? Commented Jun 10, 2015 at 20:50
  • Note that the file contents aren't quite valid JSON. Strings, including object keys, have to be delimited by double-quotes -- content of file: [{"n":100}] Commented Jun 10, 2015 at 20:51
  • aah you got invalid JSON there. you must use double quotes, not single quotes. Commented Jun 10, 2015 at 20:53

1 Answer 1

3

[{'n':100}] is not valid JSON. Change it to [{"n":100}]

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.