HTTP request and using JSON data


#1

I will use the generic ionic tabs template as an example. On the chat tabs the chats are generated by a JSON array hard coded into services JS. I want to be able to retrieve an array from an api and use it in the same way. How can I do this? This is what I have tried:

This is the services factory:

.factory('chats', function($http){
  var chats = [];

  var _loading = $http.get('https://df-local.enterprise.dreamfactory.com/api/v2/sql/_table/Deals?api_key=5be5948bd4d1323f050726c4d28c7349622b262c4b4baff463faccdb644c4a19').then(function(res){
    console.log(res.data.results);
    chats = res.data.results;
});

return {
    loading: _loading,
    all: function(){
      return chats;
    }
  };
});`

This is the controller:

.controller('ChatsCtrl', function($scope, Chats) {

$scope.chats = [];
  chats.loading.then(function(){
    $scope.chats = chats.all();
  });
})

and the HTML:

<ion-view view-title="Chats">
<ion-content>
<ion-list>
  <ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="chat in chats" type="item-text-wrap" href="#/tab/chats/{{chat.id}}">
    <img ng-src="{{chat.image}}">
    <h2>{{chat.title}}</h2>
    <p>{{chat.name}}</p>
    <i class="icon ion-chevron-right icon-accessory"></i>
  </ion-item>
</ion-list>
</ion-content>
</ion-view>

Can anyone correct the problem?

Thanks!


#2

I don’t see a ‘results’ in your response.data, but a ‘resource’.


#3

First of all on thing that is probably a problem here is that the factory you created is called charts (all lowerCased). But when you inject the factory into the Controller you use the name Charts (upperCase C). But i would still make some changes to the code. There is no need to make to separate functions in the service, one to make the API call and one to get the Data. Just combine that into one function.

This is how i would do this.

//Service
.factory('ChatsFactory', function($http){

    return {
        getData: getData
    };

    function getData() {
        return $http.get('https://df-local.enterprise.dreamfactory.com/api/v2/random-stuff').then(function(response) {
            return response;
        }, function(error) {
            return error;
        });
    }
});

//Controller 
.controller('ChatsCtrl', function($scope, ChatsFactory) {
    $scope.chats = [];
    ChatsFactory.getData().then(function(response) {
        $scope.chats = response.data; 
    });
});

One other thing, i would strongly recommend changing the URL of the http request before posting to forums when asking for help so that the API key you are using in the application does not become public like you have done here.