Nick Ko
Nick Ko

Reputation: 465

Angular, controller & service interaction to display json data

I'm new in Angular 1.5+ and I'm having some small issues with the basics, such as displaying data from a JSON file on the DOM.

So, I'm able to fetch the data fine, (I think, since it console logs okay)

But, then I'm not too sure how to interact with it on the controller, so that it's used on the html

Service

export default class Gsheets {
    constructor($http){
        'ngInject';

    this._$http = $http;


    var gData = this;

    this._$http({
        method: 'GET',
        url: 'https://jsonplaceholder.typicode.com/posts',
    })
    .then(function(response) {
    console.log(response.data);
    gData.headers = response.data;
    }, function() {
        alert("Error");
    });
}

}

Controller

(What do I have to do here?)

class EditorCtrl {
  constructor( Gsheets) {
    'ngInject';


    this._Gsheets = Gsheets;
    }
}

HTML

       <ul>
         <li ng-repeat="header in $ctrl.gData.headers"></li>
         {{header}}
       </ul>

Thank you in Advance, and any help will be much appreciated.

Regards,

Upvotes: 0

Views: 65

Answers (1)

Chris
Chris

Reputation: 6631

You store the response headers in a member of the Gsheets instance and the Gsheets instance as _Gsheets in the EditorCtrl.

So you need to reference it like this:

<ul>
  <li ng-repeat="header in $ctrl._Gsheets.headers">{{header}}</li>
</ul>

Upvotes: 2

Related Questions