Outputting JSON Data from Local Web Server onto Io

2019-06-09 08:45发布

问题:

CHALLENGE

I am trying to output the following JSON via Angular JS into my Ionic Framework Starter Side-Menu App and currently the only response that I get from my Console Log is the following:

0     825606   log      ApiEndpoint, [object Object]
1     825809   log      Got some data: , [object Object]
1     825883   log      Got some data: , [object Object]

Unfortunately as a result of this, I'm unable to display my product list within products.html

JSON Output from my Web Server [node.js server with MongoDB database local]

My webserver output is available at http://localhost:8080/api/products

[
{
_id: "55be0d021259c5a6dc955289",
name: "Apple",
price: 2.5
},
{
_id: "55be0d541259c5a6dc95528a",
name: "Oranges",
price: 1.5
},
{
_id: "55be0d6c1259c5a6dc95528b",
name: "Pear",
price: 3
},
{
_id: "55be0d6c1259c5a6dc95528c",
name: "Orange",
price: 3
}
]

services.js

angular.module('starter.services', [])

.factory('Api', function($http, ApiEndpoint) {
  console.log('ApiEndpoint', ApiEndpoint)

  var getApiData = function() {
    return $http.get(ApiEndpoint.url + '/products')
      .then(function(products) {
        console.log('Got some data: ', products);
        return products;
      });
  };

  return {
    getApiData: getApiData
  };
})

controllers.js [Relevant code]

.controller('ProductsCtrl', function($scope,Api) {
  $scope.products = null;
  Api.getApiData()
  .then(function(result) {
    $scope.products = result.products;
  })

ionic.project

{
  "name": "grocerApp",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http://cors.api.com/api"
    }
  ]
}

products.html [to show off the output]

<ion-view view-title="The Grocer Shop">
  <ion-content>
    <ion-list>
      <ion-item ng-repeat="product in products">
        <a class="item item-thumbnail-left" href="#/app/products/{{product.id}}">
        <img src="http://loremflickr.com/30/30/apples">
        <h2>{{product.name}}</h2>
        <p>EUR {{product.price}} per kilogram</p>
      </a>
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

app.js [Relevant code]

angular.module('starter', ['ionic', 'starter.controllers','starter.services'])

.constant('ApiEndpoint', {
  url: 'http://localhost:8080/api'
})

Unfortunately the following links did not help me out :

Ionic/Angular App not reading json data from api

Getting data from a json file in IONIC using AngularJS

I also double checked the file path and the JSON loads well in my local browser window[I am using Chrome with CORS extension enabled - https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en ]

QUESTION

How can I get my JSON Data from my local webserver into my products.html file?

回答1:

your service and controller is a bit wrong try the following

services.js

angular.module('starter.services', [])
    .factory('Api', function($http, ApiEndpoint) {
        console.log('ApiEndpoint', ApiEndpoint);

        var getApiData = function() {
            return $http.get(ApiEndpoint.url + '/products');
        };

        return {
            getApiData: getApiData
        };
})

controllers.js

.controller('ProductsCtrl', function($scope,Api) {
  $scope.products = null;

  Api.getApiData().then(function(result) {
          $scope.products = result.data;
  });

EDIT: Further explanations

So your first problem was returning a promise and trying to resolve it in multiple places.

return $http.get(ApiEndpoint.url + '/products')
  .then(function(products) {
    console.log('Got some data: ', products);
    return products;
  });

Api.getApiData()
.then(function(result) {
    $scope.products = result.products;
 })

Best practice is that your service returns the promise, which $http already does. You should then handle how that promise is resolved in the controller so basically what I did was just remove the .then from your factory.

The next error you had was trying to call result.products inside then function. How a promise resolves is nesting the entire body in a json object with the data attribute. So in this case your response is looking like {'data': [array_of_fruit]}. If your response were to return {'products':[array_of_fruit]} then you would still have to access like result.data.products.

Hope this helps.