Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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);
});