Outputting JSON Data from Local Web Server onto Ionic App using Angular - json

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?

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.

Related

VueJS doesn't show data on a component but shows on console

I have two pages - Books and Book. I am trying to show some data on my Book page after clicking the single item from the Books page.
I have managed to fetch the JSON file which lists all the items on the Books page as well as a link to navigate to the Book page by id.
The problem I am facing is I can't fetch the data which is returned by JSON on the Book page. The data is hidden but console.log(response.data) shows response data on console without a problem.
Here is the route-link from the Books page which navigates a single Book:
<router-link :to="'/books/' + book.id"> Link </router-link>
And here is my Book component script
<script>
import LibraryDataService from "../services/LibraryDataService";
export default {
name: "Book",
data() {
return {
book: "",
};
},
methods: {
getBook(id) {
LibraryDataService.get(id)
.then((response) => {
this.book = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
},
mounted() {
this.getBook(this.$route.params.id);
},
};
</script>
Any help will be appreciated
Try to wait for response:
async mounted() {
await this.getBook(this.$route.params.id);
},
I have been able to solve the issue by modifiying response.data on the getBook method as this.book = response.data[0];

Calling a local json file and parsing data in ReactJS

I have the following json file. Right now, i have kept this in my ReactJS project itself locally. Later on planning to move in a server location.
abtestconfig.json
[
{
"abtestname": "expAButton",
"traffic": 1,
"slices":
[
"orange",
"blue"
]
},
{
"abtestname": "expTextArea",
"traffic": 0.5,
"slices":
[
"lightgrey",
"yellow"
]
}
]
I want to read and get data and parse it and apply in a function. I got some reference sample code and trying to use fetch api to react json file with the following code.
After reading this json file, i will have to pass the data in abtest function, as you can see now it's sending with hard coded value abtest('expAButton', 0.75).slices('orange', 'blue').run(function ()
I have the following doubts and wanted to get your guidance / clarification.
1. Is it correct way to read json file using fetch api? Is there any other best approach?
2. When I use fetch api like mentioned below, console log displays GET http://localhost:8080/abtesting/abtestconfig.json 404 (Not Found)
app.jsx file:
import './abtesting/abtestconfig.json';
class App extends React.Component {
constructor() {
super();
this.onClick = this.handleClick.bind(this);
this.onClickNewUser = this.handleNewUser.bind(this);
this.state = {
bgColor: '',
data: []
}
};
handleNewUser (event) {
abtest.clear();
window.location.reload();
}
render() {
return (
<Helmet
/>
<p><b>A/B Testing Experience</b></p>
<div className="DottedBox">
<p><button id = "newUserButton" onClick = {this.onClickNewUser} style={{backgroundColor:"red"}}>Welcome and click here</button></p>
</div>
);
}
handleClick () {
abtest('expAButton', 0.75).slices('orange', 'blue').run(function () {
expAButton.style.backgroundColor = this.slice.name;
});
}
setStyle (stylecolor) {
this.setState({
bgColor: stylecolor
})
}
componentDidMount () {
this.handleClick();
fetch('./abtesting/abtestconfig.json').then(response => {
console.log(response);
return response.json();
}).then(data => {
// Work with JSON data here
console.log(data);
}).catch(err => {
// Do something for an error here
console.log("Error Reading data " + err);
});
}
}
export default hot(module)(App);

Load JSON data directly into highcharts angular

I am using https://github.com/pablojim/highcharts-ng to build Highcharts in my angularjs app. As suggested on that site I am configuring my chart configs in my controller as follows:
$scope.chartConfig6 = {
options: {
chart: {
type: 'bar'
}
},
series: [{
data: [33, 55, 10, 18, 17]
}],
title: {
text: 'Agent FNOL Ranking'
},
loading: false
}
Now I have a json file: http://pastebin.com/SEu8dHkB if you do a search you can find the field called "highChart" on the json which contains the configurations for a highchart. Now I want to be able to use these configurations directly from the json to to my highcharts config either in the controller or as a directive. This is how I get the json file via http in my service:
.factory('Swoop',function($http,$filter,$q){
return {
all: function(){
var deferred = $q.defer();
$http.get("swoop.json").success(
function(data){
// angular.copy(data, studies);
deferred.resolve(data);
}
);
return deferred.promise;
}
}})
However, I am not sure how I could render this data(under the highChart object in the json) to the $scope.chartConfig6 like I did above. Can someone please show me how this could be done?

Angularjs : $resource encapsulate the json into an object

I have a $resource called Livres I need to send to my API that wait a json typed like this :
{livres: {
id: 1
name: "bidule"
}}
This is the resource :
angular.module('TestApp').factory('Livres', [
'$resource', function($resource) {
return $resource('api/v1/livres/:id', {
id: '#_id'
}, {
update: {
method: 'PUT'
}
});
}
]);
And the called method to save :
$scope.addLivres = function() { //create a new livres. Issues a POST to /api/livress
$scope.livres.$save(function() {
$state.go('adminLivres'); // on success go back to admin home i.e. adminLivres state.
});
};
This only send a json like
{id: 1
name: "bidule"}
How can I make the json send to be encapsulated into a livres {} ?

AngularJS - How to data bind an object within a JSON object

Using the included http post, I should get back the JSON object below. I want to take the LeagueDictionary data in the JSON below and create an object so I can use it in a for each loop on my client, but I can't wrap my head around how to structure that code in the http call.
{
"Id": 0,
"UserName": null,
"NickName": null,
"Email": "email#company.com",
"Password": null,
"Admin": false,
"Validated": false,
"Key": "oOE0QbOhjK17pNeKDPEFti5On27R3b",
"LeagueDictionary": {
"1": "League #1",
"2": "League #2"
}
}
using this call:
$scope.getLeagues = function() {
$http({
method: 'POST',
url: 'http://xxxxxxxxxxxxxxxxxx',
data: ???,
})
}
If someone give me a nudge on how to data bind that particular part of the JSON, I'd appreciate the help. I'm not sure how to strip the LeagueDictionary section out and make an object out of it.
You could set up a service that gets your data, so you can get $http and such out of your controller. Say...
app.factory('DataService', function ($http) {
return {
get: function () {
return $http.get('data.json'); // post & url goes here
}
};
});
In your controller, use then to access the response data after promise has been resolved (catch() and finally() are available, too).
app.controller('MainCtrl', function ($scope, DataService) {
DataService.get().then(function (response) {
$scope.leagueDictionary = response.data.LeagueDictionary;
});
});
Related HTML template would be
<body ng-controller="MainCtrl">
<div ng-show="leagueDictionary">
<span ng-repeat="(key,val) in leagueDictionary">
{{ val }} <br>
</span>
</div>
</body>
Using your data this gives you
See example plunker here http://plnkr.co/edit/j6bmmQ
You can just access the LeagueDictionary property of the response, and then iterate over that in ng-repeat. Obviously I don't know exactly what your scopes look like, but this should get you started:
//JS
$http.post('/someUrl', { 'foo': 'bar' }).success(function(data) {
myController.myModel.leagueDictionary = data.LeagueDictionary;
});
//HTML
<tr ng-repeat="(leagueNum, leagueName) in leagueDictionary">