Tiz
Tiz

Reputation: 423

ionic retrive data from database with http request

I'm tring to learn how to use Ionic framework,

I've made a controller to get some data from a database using play 2.0 as web server. This is my factory code :

    .factory('Projects', function($http) {
    var projects =  [];
    return {
        getProjects: function() {



            $http.defaults.headers.post['Content-Type'] = 'application/json';       
            return $http({
                            method: 'POST', 
                            url: 'http://localhost:8101/getProjects', 
                            dataType: 'json',
                            headers: { 'Content-Type': undefined }

            }).success(function(data, status) {

                projects= data;
                return projects

            }).error(function(arg) {
            alert("error ");
        });
        }
    }
})

and my controller :

.controller('RootsCtrl', function($scope, Projects, $http) {

    $scope.projects= Projects.getProjects();


})

and here is my view :

<ion-view view-title="Projects">
  <ion-content>
    <ion-list>
      <ion-item class="item-remove-animate item-avatar item-icon-right" ng-repeat="project in projects" type="item-text-wrap" >
        <h2>{{project.try}}</h2>          
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

The web server only return some fake data by now.

I can't understand why, in my view, the value for project.try isn't show, but the row is present. So if I have two values, in my html I can see two row, but without their "name". Thanks

Upvotes: 0

Views: 1013

Answers (1)

InfinitePrime
InfinitePrime

Reputation: 1776

Factories are singletons and return an object that contains the members of the service.

.factory('Project', function($http, $log) {
  return {
    getProjects: getProjects
  };

  function getProject(){
    var config = {
      method: 'POST', 
      url: 'http://localhost:8101/getProjects', 
      headers: { 'Content-Type': undefined }
    }
    return $http(config).then(success).catch(failure);
  }

  function success(resp){
    return resp.data;
  }

  function failure(error){
    return error;
  }
});

$http returns a promise.

//Controller

.controller('RootsController', function(Project){
  var vm = this;

  fetchProject();

  function fetchProject(){
    Project.getProject().then(success, failure);
  }

  function success(data){
    vm.projects = data;
  }

  function failure(err){
    // Error Handling
  }
});

In your view:

<ion-item ng-repeat = "project in vm.projects">
  {{project}}
</ion-item>

Also in your states:

controller: 'RootsController as vm' because Ionic has issues with controllerAs syntax.

Also you are not posting any data? And you can see just rows and not names because the project object exists but might not contain a key called try

Upvotes: 1

Related Questions