0

Fairly new to Angular, been used to ASP/MVC/C#/Jquery for years so a bit of a learning curve. However, I'm having an issue with something I think should be simple, and based on my knowledge from other frameworks isn't working as expected.

So I have a get request to an API controller which returns data like this:

{"user":{"FirstName":"John","LastName":"Smith","EmailAddress":"[email protected]"}}

Module:

(function() {
"use strict";
//Getting the existing module
angular.module("appName")
    .controller("userDataController", function($scope, $http) {
        $http.get("/api/user")
            .then(function (response) {
                //Example response 
                //{"user":{"FirstName":"John","LastName":"Smith","EmailAddress":"[email protected]"}}
                $scope.userData = response.data;
            });
    });
})();

If I output in my view {{userData}} I get the string of data displayed, as i understand scope is given to the variable named.

However, I cant seem to display the individual data, eg: FirstName.

I have tried an ng-repeat on the userData object but that doesn't do anything., Ive also tried various things to display FirstName or EmailAddress but no luck. Am I doing something fundamentally wrong?

1
  • Does the API return a stringified version of the data? If so, use JSON.parse(response.data) Commented Mar 1, 2016 at 21:20

2 Answers 2

1

Assuming it is actually a JSON object: {{userData.user.FirstName}}

Otherwise:

$scope.userData = angular.fromJson(response.data)

And then you can still use the code above.

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

3 Comments

That's done the job, thanks. Would it be expected behavior though to use the function angular.fromJson to deserialize the object to pass back? Not seen that in any examples. Guess I probably need to actually fix the API controller function.
It really shouldn't need to be deserialized so long as your API controller is actually returning an Object. The string would be useless to you in pretty much any context so it shouldn't be sent. The fromJson at least gets you moving until it can be fixed though.
Fixed it properly now so at least I dont have to do the fromJson function and can just use {{userData.EmailAddress}} Thanks for the clarification, helps if I did it properly in the first place.
0

May be the response is content type text and not json as expected? Have a look at the response headers.

1 Comment

Response type is definatily json. Content-Type:application/json; charset=utf-8

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.