B
B
beduin012015-12-02 16:05:19
JavaScript
beduin01, 2015-12-02 16:05:19

Am I reading JSON correctly?

I'm trying to read JSON into a variable, but I'm getting an error. Here is the code itself:

$scope.questions = $http.get('js/questions-content.json').success(function(response) {
         return response.data;
        // console.log(response.data);
    });

In theory, return should perform the assignment to $scope.questions, right?
The error is like this:
SyntaxError: Unexpected token ,
    at Object.parse (native)
    at fromJson

JSON itself is like this:
[{"id":1},{"id":2}]
What could be the problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
bromzh, 2015-12-02
@beduin01

If you call success, then the callback argument is no longer response, but response.data.
If you call then, then there is a response.
I could have tried deriving the success callback argument myself before asking.
Well, from a promise you get not a value, but only a promise. So the $scope.questions variable will contain the promise of the result, not the result itself.

$http.get('js/questions-content.json').success(function(questions) {
         $scope.questions =  questions;
    });
// Но лучше так:
$http.get('js/questions-content.json').then(function(response) {
         $scope.questions =  response.data;
    });

D
Dmitry Belyaev, 2015-12-02
@bingo347

Because it's done asynchronously:

$http.get('js/questions-content.json').success(function(response) {
         return response.data;
        // console.log(response.data);
    });

When you make an assignment, the response object has not yet been received, so you need to do this:
$http.get('js/questions-content.json').success(function(response) {
         $scope.questions =  response.data;
    });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question