AngularJS $http.get JSON file returns undefined - angularjs

I am trying to get data from a JSON file to display in my AngularJS app using $http.get(...). When I run an alert with JSON.stringify, the alert says 'undefined'. Here is my code:
JS
var pplApp = angular.module('pplApp', [ 'ngAnimate', 'ngSanitize', 'utilServices' ]);
pplApp.controller('pplCtrl', function($scope, $http) {
$http.get('people.json').then(function(data) {
alert(JSON.stringify(data.People));
$scope.peoples = data.People;
});
});
JSON
{
"People": [
{
"name": "Andrew Amernante",
"rating": 3,
"img": "http://www.fillmurray.com/200/200",
"Description": "Gluten­free cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage",
"Likes": [
"Dogs",
"Long walks on the beach",
"Chopin",
"Tacos"
],
"Dislikes": [
"Birds",
"Red things",
"Danish food",
"Dead Batteries"
]
}
]
}
What am I missing?
Update: Here is my app in Plunker

The result is a response object (not the data itself). You can access the data as response.data
pplApp.controller('pplCtrl', function($scope, $http) {
$http.get('people.json').then(function(response) {
alert(JSON.stringify(response.data.People));
$scope.peoples = response.data.People;
});
});

you should not use dot operator with JSON.stringify since its just a string, change it as,
alert(JSON.stringify(data));

Here data is a JSON string not object, so you can not use data.People, instead you just need to pass data to JSON.parse.
var pplApp = angular.module('pplApp', [ 'ngAnimate', 'ngSanitize', 'utilServices' ]);
pplApp.controller('pplCtrl', function($scope, $http) {
$http.get('people.json').then(function(data) {
var response = JSON.parse(data);
$scope.peoples = response.People;
});
});
I checked with your json string and works using following code.
var json = '{"People": [{"name": "Andrew Amernante","rating": 3,"img": "http://www.fillmurray.com/200/200","Description": "Gluten­free cray cardigan vegan. Lumbersexual pork belly blog, fanny pack put a bird on it selvage","Likes": ["Dogs","Long walks on the beach","Chopin","Tacos"],"Dislikes": ["Birds","Red things","Danish food","Dead Batteries"]}]}';
var response = JSON.parse(json);
$scope.peoples = response.People;

Related

How to convert string into JSON data in view part of angularjs

Hi I have this data in JSON form, and I want to convert this data of option into json so that i can call optionName, optionSubName in a view part of angularjs
[
{
"heading": "MakeUp Type / Selection",
"option": "{"optionName":"Bridal Makeup","optionSubName":"Engagement,Tika / Godh Bharai,Ring Ceremony","optionDesc":""}",
"values": null
},
{
"heading": "Makeup Type",
"option": "{"optionName":"Experienced","optionSubName":"","optionDesc":{"products":"Bobbie Brown,Makeup Forever and Premium Makeup Products","Makeup_Include":"Straightening,Blow Drys,Tong Curls,Updo's","Drapping":"Yes","Lashes":"Yes","Nail_Polish_Change":"Yes","Extension_Available":"Yes","Airbrush_Available":"Yes"}}",
"values": null
}
]
I have already tried this but this is not working by using ng-repeat i have using this {{data.option.optionName | JSON}} but this is not working in my view part of angularjs, Please help me out how to reach at my goal ?
Use AngularJS forEach:
angular.forEach(object, iterator, [context])
object: The object interate over.
iterator: The iterator function or the code.
context: Object to become context (using this) for the iterator function.
var app = angular.module('app', []);
app.controller('AppController', ['$scope', '$http',
function($scope, $http) {
$http.get('json/array.json').success(function(data) {
$scope.array = data;
angular.forEach($scope.array, function(x){
console.log(x.optionName);
})
});
});
}
]);

Reading JSON file content using AngularJs

I am trying to read and display publications and permissions section from JSON file below using angularjs. I am trying to display idno and title values from publications node and tou, resolution and terms values from permissions nodes. Bun when I try to run below code I am getting blank page.
Here is my HTML and Js code-
<div ng-controller="rFind">
<p>The ID is {{pubs.idno}}</p>
<p>The content title is {{pubs.title}}</p>
</div>
angular.module('demo',[])
.controller('rFind', function ($scope, $http) {
$http.get('rfind.json').success(function (data) {
$scope.pubs = data.publications;
});
});
JSON File -
{
"location": "US",
"publications": [
{
"idno": "1360-0869",
"workId": "122936490",
"title": "INTERNATIONAL REVIEW OF LAW (1996- )",
"permissions": [
{
"tou": "DIGITAL",
"resolution": "GRANT",
"terms": [
{
"code": "d0214dec",
"description": "This journal title may publish some Open Access articles, which provide specific user rights for reuse."
},
{
"code": "93bfc4ca",
"description": "User may not include copies of portions of this Work in presentations shown to external audiences."
}
]
},
{
"tou": "PRINT",
"resolution": "GRANT",
"terms": [
{
"code": "d0214dec",
"description": "This journal title may publish some Open Access articles, which provide specific user rights for reuse."
}
]
},
{
"tou": "REACTIVELY_SHARE",
"resolution": "GRANT",
"terms": [
{
"code": "d0214dec",
"description": "This journal title may publish some Open Access articles, which provide specific user rights for reuse."
}
]
}
],
"startYear": 1996,
"customMessages": [ ],
"publishers": [ "ROUTLEDGE" ]
}
]
}
Not sure what's wrong with my code. Any help will be appreciated.
Thanks!
Publications is returning as an array, you need to do one of two things - fix the endpoint so it returns an object, or use the Array prototype find to grab the object, or grab the first index if it exists. You're trying to reference the object when it is an array.
$scope.pubs = data.publications[0];
$scope.pubs = data.publications.find(record => record.idno === param.id);
Or you can do a ng-repeat on scope.pubs.
Can you try this?
angular.module('demo',[])
.controller('rFind', function ($scope, $http) {
$http.get('rfind.json').then(function (data) {
$scope.pubs = data.data.publications;
});
});
Thanks all for your responses. This is what finally worked for me -
rf.js
var myApp = angular.module('myApp', []);
myApp.controller('rFind', ['$scope', '$http', function ($scope, $http) {
$http({
method: "GET",
url: "/js/rf.json"
}).then(function mySuccess(response) {
$scope.posts = response.data;
$scope.pubs = response.data.publications;
}, function myError(response) {
$scope.myWelcome = response.statusText;
});
}]);
rf.htm
<body ng-app='myApp'>
<div ng-controller='rFind'>
<p>ID: {{ posts.location }} </p>
<div ng-repeat="pub in pubs">
<p> idn: {{pub.idno}} - {{pub.title}}</p>
<div ng-repeat="perm in pub.permissions">
<p> -> {{perm.tou}} : {{perm.resolution}} </p>
<div ng-repeat="trm in perm.terms">
<p>{{trm.description}}</p>
</div>
</div>
</div>
</div>>
</body>

How do I get a single value from a json file using angular (without using ng-repeat)?

I have a json file with the following data:
{
"favicons": [
{
"36x36”: "36x36.png",
"48x48": "48x48.png",
"57x57": "57x57.png"
}
],
"header": [
{
"imageUrl": "logo.png",
"subTitle": “blah”,
"backgroundColor": "#c30909"
}
]
}
I'd like to retrieve the value of favicons.36x36 without using ng-repeat.
I have this in my app.controller:
app.controller('myCtrl', function($scope, $http) {
$http.get("data.json").then(function (response) {
$scope.faviconData = response.data.favicons;
})
});
Using {{faviconData}} in my HTML, I can output the entire array.
But {{faviconData.36x36}} results in a parse syntax error.
I have also tried faviconData[0].36x36 but this also results in an error.
Do this
{{faviconData[0]['36x36']}}

How to access "Title" from this JSON object, using AngularJS

Cinemalytics API endpoint, which gives a JSON output:
http://api.cinemalytics.com/v1/movie/releasedthisweek?auth_token=[token]&callback=JSON_CALLBACK
How to access "Title" from this JSON object, using AngularJS
[
{
"Id": "b2a1844b",
"ImdbId": "tt0315642",
"OriginalTitle": "Wazir",
"Title": "Wazir",
"Description": "'Wazir' is a tale of two unlikely friends, a wheelchair-bound chess grandmaster and a brave ATS officer. Brought together by grief and a strange twist of fate, the two men decide to help each other win the biggest games of their lives. But there's a mysterious, dangerous opponent lurking in the shadows, who is all set to checkmate them.",
"TrailerLink": "https://www.youtube.com/watch?v=gdwM7xKOph0",
"TrailerEmbedCode": "<iframe width=\"850\" height=\"450\" src=\"https://www.youtube.com/embed/gdwM7xKOph0\" frameborder=\"0\" allowfullscreen></iframe>",
"Country": "IN",
"Region": "BOLLYWOOD",
"Genre": "Drama",
"RatingCount": 16,
"Rating": 3.7,
"CensorRating": "U/A",
"ReleaseDate": "1/8/2016",
"Runtime": 102,
"Budget": 0,
"Revenue": 0,
"PosterPath": "https://s3-ap-southeast-1.amazonaws.com/cinemalytics/movie/F6E428DA299F2ECEED5B4D3B1723A202.jpg"
},
{
"Id": "1e3424cb",
"ImdbId": "tt3777164",
"OriginalTitle": "Chauranga",
"Title": "Chauranga",
"Description": "A fourteen-year-old Dalit boy (Soham Maitra) is growing up in an unnamed corner of India. His dream is to go to a town school like his elder brother (Riddhi Sen) and his reality is to look after the pig that his family owns. His only escape is to sit atop a Jamun tree and adore his beloved (Ena Saha) passing by on her scooter. His unspoken love is as true as his mother’s helplessness who cleans the cowsheds of the local strongman’s mansion, with whom she also has a secret liaison. When the boy’s elder brother comes on a vacation to the village, he soon finds out about his younger brother’s infatuation. The learned elder brother makes him realize the need to express his love and helps him write a love letter.",
"TrailerLink": "https://www.youtube.com/watch?v=Nu50meFTNU4",
"TrailerEmbedCode": "<iframe width=\"850\" height=\"450\" src=\"https://www.youtube.com/embed/Nu50meFTNU4\" frameborder=\"0\" allowfullscreen></iframe>",
"Country": "IN",
"Region": "BOLLYWOOD",
"Genre": "Drama",
"RatingCount": 17,
"Rating": 3.84706,
"CensorRating": "U/A",
"ReleaseDate": "1/8/2016",
"Runtime": 90,
"Budget": 0,
"Revenue": 0,
"PosterPath": "https://s3-ap-southeast-1.amazonaws.com/cinemalytics/movie/083FFED0BC933C2D60E8891B89269EB3.jpg"
}
]
With your current URL
http://api.cinemalytics.com/v1/movie/releasedthisweek?auth_token=<auth_token>&callback=JSON_CALLBACK
you may have cross origin issues. However you can use the (https://crossorigin.me/) service to avoid this issue.
Then, you should request:
https://crossorigin.me/http://api.cinemalytics.com/v1/movie/releasedthisweek?auth_token=<auth_token>&callback=JSON_CALLBACK
Finally, this can be easily used in your AngularJS code.
I've made a demo, using an AngularJS Service and Controller.
(function() {
var app = angular.module("myApp", []);
// Service
app.service("Service", ["$http",
function($http) {
return {
getData: function() {
return $http.get("https://crossorigin.me/http://api.cinemalytics.com/v1/movie/releasedthisweek?auth_token=<auth_token>&callback=JSON_CALLBACK", null, {
responseType: "json"
});
}
};
}
]);
// Controller
app.controller("Controller", ["$scope", "Service",
function($scope, Service) {
$scope.data = [];
$scope.list = function() {
// Calling the getData() function from the Service.
Service.getData().then(function(response) {
$scope.data = response.data; // Store the response in the data variable.
}, function(response) {
console.log(response); // if there is an error...
});
};
$scope.list(); // Call to the function once.
}
]);
})();
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div data-ng-app="myApp">
<div data-ng-controller="Controller">
<ul>
<!-- As you have an array, you should use data-ng-repeat to show the items collection. -->
<!-- Use data-ng-bind to show the Title (One-way data binding). -->
<li data-ng-repeat="item in data" data-ng-bind="item.Title">
</li>
</ul>
</div>
</div>
Hope this helps.
If the JSON was in a variable movies:
movies.map(function (m) {return m.Title;});
See JSbin example.
With querying the endpoint:
$http.get('http://api.cinemalytics.com/v1/movie/releasedthisweek?auth_token=59CD0710AD10858DD65FE815F0181603&callback=JSON_CALLBACK')
.then(function(res) {
$scope.titles = res.map(function (m) {return m.Title;});
});
$scope.titles would hold the extracted titles.
With no other context or code attempts that you have shown, here is what the simple Angular GET request would look like.
angular.module('myApp', [])
.controller('myController', function($http) {
var vm = this;
getObject();
function getObject() {
return $http.get('http://api.cinemalytics.com/v1/movie/releasedthisweek?auth_token=59CD0710AD10858DD65FE815F0181603&callback=JSON_CALLBACK')
.then(function(res) {
vm.object = res.data;
});
});
<div ng-app="myApp">
<div ng-controller="myController as vm" ng-repeat="item in vm.object track by item.Id">
Item {{item.Id}} - Title: {{item.Title}}
</div>
</div>

Sub-promises in AngularFire - selecting related children by ID?

I have a json collection I've uploaded to my firebase, the sites and tools are related via arrays located in the former that point to keys in the latter
"sites": {
"s001": {
"name": "ACT-105",
"description": "Intro Accounting",
"type": "course",
"thumbnail": "debate",
"toolCount": 4,
"tools" : ["t001","t002","t003"]
},
"s002": {
"name": "ART-201",
"description": "Pottery Lab",
"type": "course",
"thumbnail": "sculpture",
"toolCount": 4,
"tools" : ["t001","t002","t003","t004"]
},
"tools": {
"t001": {
"name": "main-tool",
"title": "Home",
"description": "Main tool",
"thumbnail": "home.jpeg"
},
"t002": {
"name": "announce-tool",
"title": "Announcements",
"description": "System Announcements",
"thumbnail": "announcements.jpeg"
},
I open a url and promise; then grab the current site and its array of related tools in an array, then open another promise to loop through and get all the related tools. From the alert, it appears to only grab one tool then quits.
angular.module("foo", ["firebase"]).
controller("MyCtrl", ["$scope", "angularFire", function($scope, angularFire) {
var dbRef = "https://sampledb.firebaseio.com";
var siteRef = new Firebase(dbRef + "/sites/s003");
var promise = angularFire(siteRef, $scope, "site", {});
var sitetools = [];
promise.then(function() {
sitetools = $scope.site.tools;
alert("tools " + sitetools);
}).then(function () {
var toolList = [];
for (var i=0;i<sitetools.length;i++)
{
alert("tool " + sitetools[i]);
toolList.push(getTool(dbRef,toolId));
}
$scope.tools = toolList;
});
}]);
var getTool = function(dbRef,toolId) {
var toolitem;
var toolRef = new Firebase(dbRef + "/tools/" + toolId);
alert(toolRef);
var promise = angularFire(toolRef, $scope, "tool", {});
promise.then(function() {
alert("found tool " + toolId);
toolitem = $scope.tool;
});
return toolitem;
};
The fiddle is here: http://jsfiddle.net/5n9mj/1/
First of all, you should have got the alerts (3 of them) since the iterations went as expected, but the return of the getTool() function is always null: it returns before the promise is resolved and local tooitem variable is not accessible anymore.
Remember that all Firebase calls are async. Also, this code:
var promise = angularFire(toolRef, $scope, "tool", {});
promise.then(function() {
alert("found tool " + toolId);
toolitem = $scope.tool;
}
will trigger race conditions: $scope.tool is bound with the Firebase and there is no guarantee that it would be bound in a specific order and if there will be enough processor time to push it into your array before another promise is resolved. That's why it's better to listen on the value change using Firebase reference than to use angularFire and explicitly bind it to the scope variable.
I think you overcomplicated the code a little bit, you don't have to create new Firebase references every time you are binding your scope variables (unless you're going to use the reference later) with angularFire: angulerFire can accept String url as it's first param.
http://jsfiddle.net/oburakevych/5n9mj/10/
If I were you I would wrap the Tool functionality into a directive with a separate controller, so that each tool will have it's own scope, something like this:
<ul ng-repeat="toolId in tools">
<li><tool tool-id="{{toolId}}"/></li>
</ul>
var promise = angularFire(siteRef, $scope, "site", {});
promise.then(function() {
$scope.broadcast("event:SITE_INITIALIZED");
});
.controller("MyCtrl", ["$scope", "angularFire", '$timeout', function($scope, angularFire, $timeout) {
$scope.$on("event:SITE_INITIALIZED", function() {
angularFire(siteRef + "/item/" + $scope.itemId, $scope, "item", {});)
});

Resources