0

Trying to get JSON data from an API and show the result in a view using AngularJS. I'm able to get the data correctly but unable to show it in the view. When i try to access the object's data the result is always undefined.

Here's what i'm doing...

API Service:

myApp.service('apiService', ['$http', function($http)
{
    var api = "http://domain.xpto/api/";

    var self = this;
    this.result;

    var apiService =
    {
        getSection: function(id)
        {
            var url = api + "section/" + id;

            return $http.get(url);
        }
    }

    return apiService;
}]);

Controller:

myApp.controller('mainController', ['$scope', '$routeParams', 'apiService', function($scope, $routeParams, apiService)
{
    apiService.getSection(1).then(function(response)
    {
        $scope.$applyAsync(function ()
        {
            var data = response.data; //json data as expected
            var section = data.section; //undefined?!
            var images = data.images; //undefined!?

            $scope.title = section.title; //undefined!?         
        });
    });

}]);

JSON Result: enter image description here

UPDATE: Simplified my apiService based on @Salih's and @elclanrs's suggestion.

Why am i unable to access the inner objects of the json (f.e, data.section.title)?

UPDATE #2: I'm finally able to access the data. It seems i needed an extra data level to get access to the section object of my json array (response.data.data.section). Honesty i don't understand why. I've accessed the API using jquery and it was strait forward...

4
  • 1
    That first piece of code seems very redundant. Looks like you can replace it with getSection: function(id) { return $http.get(api + "section/" + id); } Commented Apr 8, 2017 at 0:39
  • Indeed. Updated my api service but my issue still remains. Any more suggestions? Commented Apr 8, 2017 at 1:10
  • Have you tried using JSON.parse on response.data to see if it's text? Commented Apr 8, 2017 at 1:18
  • @nixkuroi i get a SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse when i try to parse response.data. What does this mean? Commented Apr 8, 2017 at 1:29

3 Answers 3

1

Edit: I made this plunker to help you! http://embed.plnkr.co/Yiz9TvVR4Wcf3dLKz0H9/

If I were you, I would use the service function to update the own service value. You already created this.result, you can just update its value.

Your Service:

myApp.service('apiService', ['$http', function($http)
{
    var api = "http://domain.xpto/api/";

    var self = this;
    this.result = {};

    this.getSection = function(id){
        var url = api + "section/" + id;

        $http.get(url).then(function(res){
            self.result = res;
        });
    }
}]);

I wouldn't use a Promise for this case. You can access the Service's var into your Controller and View.

Your controller:

myApp.controller('mainController', ['$scope', '$routeParams', 'apiService', 
function($scope, $routeParams, apiService)
{
    $scope.apiSer = apiService;

    $scope.apiSer.getSection(1);

}]);

In your View:

<pre>{{ apiSer.result }}</pre>

And now you'll see your parameter get updated in real time.

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

5 Comments

Changed my code based on your suggestion, but i'm still not able to access the inner data values (data.section).
When i try your solution i get the following error: XMLHttpRequest cannot load domain.xpto/api/section/1. Redirect from 'domain.xpto/api/section/1' to 'domain.xpto/api/section/1' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost.site' is therefore not allowed access. angular.js:14516 Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"domains.xpto/api/secti ...
You can split your problem into two other problems. The first one is about to parse an JSON from an API (that I showed to you). The second one is about CORS. Try to use the Reddit API first (that I used in Plunker) and use this as example. After that you try to use this other API.
Solved it! i was using a wrong api address. Nonetheless, i managed to solve my issue. I've updated my question. Thx for the help, much appreciated.
Nope! It was a pleasure!
1

In your getSection function just write and return the following

return $http.get(url);

1 Comment

Updated my service and i still can't access the data. What might be causing this issue?
1

You might need to use angular.forEach method to parse your inner values of the JSON . Take a look at this example Accesing nested JSON with AngularJS

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.