Use JSON data coming from WebApi in AngularJS application - json

I get some data from a WebApi, the answer (below the code to get the datas) is in JSON. But I can't access this result from angularJS. The datas look like :
{
"$id": "1",
"result": [
{
"$id": "2",
"name": "Français",
"code": "FR",
"id": 1
},
{
"$id": "3",
"name": "Néerlandais",
"code": "NL",
"id": 2
},
{
"$id": "4",
"name": "English",
"code": "EN",
"id": 3
}
]
}
But I get the error below when I try to display the result :
data.result is undefined
I get the data like this :
(function () {
angular.module('myApp')
.factory('dataService', ['$q', '$http', dataService]);
function dataService($q, $http) {
return {
initFormCustomer: initFormCustomer
};
function initFormCustomer() {
return $http({
method: 'GET',
url: 'http://localhost:123456/api/forminit/customer/',
headers: {
},
transformResponse: transformCustomer,
cache: true
})
.then(sendResponseData)
.catch(sendGetCustomerError)
}
function sendResponseData(response) {
return response.data;
}
function transformCustomer(data, headersGetter) {
var transformed = angular.fromJson(data.result);
console.log(data.result[0]);
return transformed;
}
function sendGetCustomerError(response) {
return $q.reject('Error retrieving customer(s). (HTTP status: ' + response.status + ')');
}
}
}());
The controller :
(function () {
angular.module('myApp')
.controller('customerController', ['$location', '$scope', 'dataService', CustomerController]);
function CustomerController($location, $scope, dataService) {
var vm = this;
vm.languages = dataService.initFormCustomer();
}
}());

I think the transform function gets a json string that you have to deserialize before using it as an object... try sth like:
function transformCustomer(data, headersGetter) {
var transformed = angular.fromJson(data);
console.log(transformed.result[0]);
return transformed.result;
}
Additionally you may look at the docs https://docs.angularjs.org/api/ng/service/$http . There is some code showing how to append a transform to the default one (that do the deserialization and XSRF checks)

Related

get json value object from mongodb

I have formData node that has dynamic jsonObject value in mongodb
{
"_id": {
"$oid": "5a71fea0f36d2848ae4f8f0a"
},
"formData": {
"pages": [
{
"name": "page1",
"questions": [
{
"type": "comment",
"name": "about",
"title": "Please tell us about your main requirements "
}
]
}
]
},
"editorId": "59678e58f36d2842f777bc48",
"datetimeSubmit": "2018/01/15"
}
I write a node API to fetch the data from mongodb, it only display ids, editorI and datetimesubmit nodes, but it ignores the formData(jsondata) field.
const Model = require('./myModel');
module.exports = {
getData: function (callback) {
Model.find({}, (err, jsonObj) => {
callback(null, {
data: jsonObj
})
})
}
}
looks like the model.find() doesn't return jsonObject value?
thanks
got my own question fixed, basically, i should also define the data type as JSON in schema, otherwise, will be ignored.

Meteor JSON Method and Call in template

I am trying to call a Meteor method with a parsed json doc to use in my template. None of my calls work and I then need advise on how to display (maybe I should save this part for another post - but any suggestions would be helpful) in template with helpers. I am new to meteor and javascript.
Json doc
{
"sports-content": {
"sport-event": [{
"event-metadata": {
"league": "NCAA Basketball",
"event-type": "0",
"league-details": "NCAAB",
"event-date-time": "12/18/2015 07:00 PM",
"eventNum": "3000460",
"status": "",
"off-the-board": "False"
},
"team": [{
"team-metadata": {
"alignment": "Home",
"nss": "526",
"openNum": "526",
"name": {
"full": "Clemson"
}
},
"wagering-stats": {
"wagering-straight-spread": {
"bookmaker-name": "BetOnline",
"active": "true",
"line": "1.5",
"money": "-110",
"context": "current"
}
},
"team-stats": {
"score": "0"
}
}, {
"team-metadata": {
"alignment": "Away",
"openNum": "525",
"nss": "525",
"name": {
"full": "South Carolina"
}
},
"wagering-stats": {
"wagering-straight-spread": {
"bookmaker-name": "BetOnline",
"active": "true",
"line": "-1.5",
"money": "-110",
"context": "current"
}
},
"team-stats": {
"score": "0"
}
}]
}],
"sports-meta-data": {
"doc-time": "42353.5979256944"
}
}
}
server.js
Meteor.startup(function () {
Meteor.methods({
sportsFeed:function(){
//console.log(JSON.parse(Assets.getText('ncaab.json')));
var feed = {};
var feed = JSON.parse(Assets.getText("ncaab.json"));
return feed;
}
});
});
Template.html
<template name="tabsOne">
<p>{{display}}</p>
</template>
Template.js
Template.tabsOne.helpers({
display: function(){
Meteor.call('sportsFeed', function(error, result){
if(error){
console.log("error", error);
}
if(result){
console.log('success');
}
});
}
});
If the json file is from your local, thinking about save it into Mongo and then publish it to the client
First, you need to create a collection called SportContent and on the server side, just make
SportContent.insert(JSON.parse(Assets.getText("ncaab.json")));
and then, do the normal publication to the client
If the json file is not on your local side (as in, you get it from rest call service), use wrapAsync to wrap the Http.call, then trigger the rest call and return the result. On your client side, you will get the response
Example on the server side to connect to the rest api
Meteor.methods({
'updateFeed': function () {
var httpCall = Meteor.wrapAsync(HTTP.call);
var result = httpCall('GET', url, {headers: headers});
....
}
});

How to display data from a json file in angularjs?

I have a json something like this
{
"count": 67,
"0": {
"id": "2443",
"name": "Art Gallery",
"category": {
"id": "2246",
"name": "Gifts & Memories"
},
"deckLocation": [
{
"id": "2443",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
},
"1": {
"id": "7198",
"name": "Captain's Circle Desk",
"category": {
"id": "352",
"name": "Other Services"
},
"deckLocation": [
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
},
{
"id": "7198",
"deck": {
"deckNo": "7",
"deckName": "Promenade "
},
}
]
}
}
I want to display all names which is inside the "0", "1" array. I can able to list a specific name but not all. The fist name will display which I written in the following code. But I need to display all 0, 1, 2, 3 etc names dynamically.
data[0].name
Please help me.
Thank you.
use ng-repeat function to do so.
<div ng-repeat = "names in data">
<P>{{names.name}}</P>
</div>
Let us say you have a service like this:-
var todoApp = angular.module("todoApp",[]);
todoApp.factory('dbService', ['$q','$http',function ($q , $http) {
var service ={};
service.getUrl = function (urlToGet) {
var svc=this;
var deferred = $q.defer();
var responsePromise = $http.get(urlToGet);
responsePromise.success(function (data, status, headers, config) {
deferred.resolve(data); });
responsePromise.error(function (data, status, headers, config) {
deferred.reject({ error: "Ajax Failed", errorInfo: data });});
return (deferred.promise);
}
return service;
}]);
And you want to load a file named '/js/udata.json'. Here is how in you controller you can load this file:-
todoApp.controller("ToDoCtrl", ['$scope','$timeout','dbService',function($scope, $timeout, dbService)
{
$scope.todo={};
$timeout(function(){
dbService.getUrl('/js/udata.json').then(function(resp){
$scope.todo=resp;
});},1);
};
Hope this helps!
You have data[0].name right?
then why don't you loop through that to get all the name elements in those arrays.
like...
for(i=1;i<data.length;i++)
{
console.log(data[i].name);
}

AngularJS display JSON data in table

I am using AngularJS with RESTAPI, I am able to get the customers data sent from server in a JSON format. My Angular code snippet as below:
app.factory("services", ['$http', function($http) {
var serviceBase = '/api/album';
var obj = {};
obj.getCustomers = function(){
return $http.get(serviceBase);
};
return obj;
}]);
app.controller('listCtrl', function ($scope, services) {
services.getCustomers().then(function(data){
alert(JSON.stringify(data.data));
$scope.customers = data.data;
});
});
Here is my JSON data:
{
"data": [
{
"id": "1",
"artist": "Gotye75",
"title": "Making Mirrors7"
},
{
"id": "100",
"artist": "ytttt5",
"title": "1231"
},
{
"id": "101",
"artist": "65",
"title": "565444555"
},
{
"id": "102",
"artist": "6",
"title": "6"
},
{
"id": "103",
"artist": "y",
"title": "yy"
},
{
"id": "104",
"artist": "ty",
"title": "yt"
},
{
"id": "109",
"artist": "ytrer",
"title": "yt"
}
]
}
I am able to display the JSON data in table if my JSON does not contain the "data" hear. However if my jSON data comes with "data" header, it is unable to display. I am asking, what are the solution in Angular to parse the JSON object.
For example if it is in BackboneJS, i can simply do
parse: function (response) {
//alert(JSON.stringify(response.data));
return response.data;
}
How can i do it in Angular?
$http resolves its promises with a response object. The data is accessed via the response object's data property. So to get to the array, you'd have to use
$scope.customers = data.data.data;
$http's promise is enhanced with a .success() convenience method which unwraps the response object...
services.getCustomers().success(function(data){
alert(JSON.stringify(data.data));
$scope.customers = data.data;
});
I solved it by
app.controller('listCtrl', function ($scope, services) {
services.getCustomers().then(function(data){
//notice that i added the third data
$scope.customers = data.data.data;
});
});

Backbone JS parse json attribute to a collection's model

I'm having trouble parsing a json to a model.
Here is the JSON:
[
{
"name": "Douglas Crockford",
"email": "example#gmail.com",
"_id": "50f5f5d4014e045f000002",
"__v": 0,
"items": [
{
"cena1": "Cena1",
"cena2": "Cena2",
"cena3": Cena3,
"cena4": "Cena4",
"cena5": "Cena5",
"cena6": Cena6,
"_id": "50ee3e782a3d30fe020001"
}
]
}
]
And i need a model to have the 'items' attributes like this:
cena = new Model({
cena1: "Cena1",
cena2: "Cena2",
...
});
What I've tried:
var cenaCollection = new Backbone.Collection.extend({
model: Cenas,
url: '/orders',
parse: function (response) {
return this.model = response.items;
}
});
then I create new instance of the collection and fetch, but i get "response.items" always "undefined" :|
Thanks in advance!
The parse function should return the attributes hash to be set on the model (see the documentation here). So you'll need simply:
parse: function (response) {
return response[0].items;
}