Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript AngularJS Basics (1.x) Services in Angular Using Services To Get Data

JSON object being parsed into a string?

For some reason my JSON object is being parsed over using the $http.get service into a string? I have tried re-structuring it into a regular array, and it sill being translated as a string? I have no idea why it is doing this.

Here is my JSON object (document named cloudTerms.json):

[
    {category: "secondary",
    term: "test1" }
];

Here is my service and controller:

angular.js
angular.module("todoListApp",[])

.controller("mainCtrl", function($scope, dataService){

    $scope.addTerm = function(){ };

    dataService.getCloudTerms(
        function(response) {            
            console.log(response.data);
            $scope.cloudTerms = response.data;
            console.log($scope.cloudTerms);
        }
    );

})

.service("dataService", function($http){

    this.getCloudTerms = function(callback){
        $http.get('data/cloudTerms.json')
        .then(callback);
    }

})

and here's my html:

      <div id="themeCloud" ng-controller="mainCtrl">

          <div class="output" ng-repeat="cloudTerm in cloudTerms">
            <h1>{{cloudTerm.category}}</h1>
            <h2>{{cloudTerm.term}}</h2>
              <hr/>
          </div>

          {{cloudTerms}}

      </div>

Again, keep in mind the data IS being successfully transferred over, but the application is rendering it as a string rather than an array. Thanks!

1 Answer

akak
akak
29,445 Points

Try parsing the json before using it:

dataService.getCloudTerms(function(response) {            
  $scope.cloudTerms = JSON.parse(response.data);
});