retrieve json data using GET in angularjs - json

I've got some data stored in a nosql database that I'm able to see in when accessing localhost:3000/countries.
I'm trying to use this factory in order to get the data which is in json.
.factory('countries', ['$http', '$q',
function($http, $q) {
var countries = {
get: function() {
return $q(function(resolve, reject) {
$http({
method: 'GET',
url: '/countries'
}).then(function(response) {
resolve(response.data);
}, function(error) {
reject(error);
});
});
};
return countries;
}
]);
And then I'm attempting to use this controller to send that data to the appropriate url to be displayed but it isn't working as I expected it to.
.controller('CountriesCtrl', function($scope, countries) {
console.log(countries);
countries.get(function(countries) {
$scope.countries = countries;
});
})
Any thoughts or suggestions? Thanks!

This is what I use currently in my project that uses Mongodb
cmsApp.factory("tasks", ["$resource", function($resource) {
return $resource("/tasks/", {}, {
save: {
method: 'POST',
isArray: true
},
'delete': {
method: 'DELETE',
isArray: true
}
});
}]);
Then in the Controller(make sure to inject it to controller!):
$scope.tasks = tasks.query();
.query() selects all of the data while .get() gets on by Id

You should inject your factory into your controller, something like this:
.controller('CountriesCtrl', function($scope, devices) {
console.log(countries);
countries.get(function(data) {
$scope.data = data;
});
})

You should inject service 'devices' instead of it's internal variable 'countries'.
.controller('CountriesCtrl', function($scope, devices) {
console.log(devices);
devices.get().then(function(countries) {
$scope.countries = countries;
});
});

Related

Angular- Couldnot parse json response in front-end

I made an httpRequest fetch some items using following code:
factory.getBanners = function() {
$http({
method: 'GET',
url: 'http://localhost:2100/v1/items/getBanners'
}).then(function successCallback(response) {
console.log(response);
return response;
});
};
In controller I handled it as following:
store.controller('bannerCtrl', ['$scope', 'productService', function($scope, productService){
$scope.init = function() {
$scope.banners = productService.getBanners();
}
$scope.init();
}]);
In front end I tried to display data using
<div ng-controller="bannerCtrl">
<div data-ng-repeat="banner in banners">
<li> {{banner.bannerAltText}} </li>
</div>
</div>
But it doesn't display anything. Neither it gives any error on console. How can I resolve this issue. Here banners is an array whose each element contains bannerAltText.
Your getBanners-function does not work the way you think it does. It returns nothing. The return statement in the then function only returns from that then-function, not from getBanners. The problem is that you are trying to use an asynchonous function in a synchronous way. Instead make getBanners return a promise:
factory.getBanners = function() {
return $http({
method: 'GET',
url: 'http://localhost:2100/v1/items/getBanners'
}).then(function successCallback(response) {
return response.data;
});
};
And use that promise in your controller:
$scope.init = function() {
productService.getBanners().then(function(banners) {
$scope.banners = banners;
});
}
$scope.init();
A return in a in .then() will be a promise, rather than the data. here is a better way to construct your code
factory.getBanners = function() {
return $http({
method: 'GET',
url: 'http://localhost:2100/v1/items/getBanners'
});
};
.
store.controller('bannerCtrl', ['$scope', 'productService', function($scope, productService){
$scope.init = function() {
productService.getBanners()
.then(function(response) {$scope.banners = response.data});
}
$scope.init();
}]);

AngularJS : Factory JSON Array with HTTP GET

I'm developing my first AngularJS app using the Google Docs API to pass it JSON data.
This is an example of the factory I'm using:
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true});
},
updates:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/2/public/values?alt=json', {cache: true});
},
docs:function () {
return $http.get(googleDocs + apiKeys.googleDoc +'/3/public/values?alt=json', {cache: true});
}
}]);
I wanted to clean up a bit the code and decided to use services instead of making the calls in the controller itself. It works normally, but it's a pain in the ass the fact that I still need to write long $scopes because of the structure of the Google API. This is how I get the values in the controller:
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().success(function (data) {
$scope.totalNews = data.feed.entry.length;
});
}]);
Is there a way that I can set the factory service to pass me the data just using:
$scope.totalNews = Data.news()
Or at least removing the 'feed.entry'?
Data.news().success(function (data) {
$scope.totalNews = data.length;
});
Thank you very much!
example of service - resolve the success with the data you want
app.service('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
this.news =function(){
return $http.get(googleDocs + apiKeys.googleDoc +'/1/public/values? alt=json', {cache: true})
.then(function(data){
return data.feed.entry.length;
});
}
}]);
the controller - since you already resolved the data in service hence..
app.controller('homeCt', ['$scope', 'Data', function ($scope, Data){
Data.news().then(function (data) {
$scope.totalNews = data;
});
}]);
working example
var app = angular.module('app', ['ionic'])
.service('Data', ['$http',
function($http) {
var googleDocs = 'https://spreadsheets.google.com/feeds/list/1aC1lUSxKatfxMKEy1erKDSAKgijSWOh77FDvKWhpwfg/1/public/values?alt=json';
this.news = function() {
return $http.get(googleDocs, {
cache: true
}).then(function(res) {
return res.data.feed.entry;
});
}
}
])
.controller('homeCt', ['$scope', 'Data',
function($scope, Data) {
Data.news().then(function(data) {
console.log(data);
})
}
]);
I'll give you a way of doing it, a way that I don't recommend at all (a service should not handle the scope), but for me it is the only way you have if you don't want to destroy the "async" of your ajax call :
app.factory('Data', ['$http', 'apiKeys', function($http, apiKeys){
var googleDocs = 'https://spreadsheets.google.com/feeds/list/';
return {
news:news,
updates: updates,
[...]
}
function news(scopeValue) {
$http.get(googleDocs + apiKeys.googleDoc +'/1/public/values?alt=json', {cache: true}).success(function(data){
scopeValue = data;
});
}]);
and then, call it that way in your controller :
Data.news($scope.totalNews);

angularJS add JSON by http request

want to download a JSON of beercat('bieres.json') in this.bieres
How could I do?
function() {
var app = angular.module('monStore', []);
app.service('dataService', function($http) {
this.getData = function() {
return $http({
method: 'GET',
url: 'bieres.json'
});
}
});
app.controller('StoreController', function($scope,dataService){
this.bieres = [];
dataService.getData().then(function(dataResponse) {
$scope.bieres = dataResponse.data;
});
...
});
I think it's my access by this.bieres that it's wrong,
the Json is loaded in the console, but a blank page is in result

How to load more than one json file in angular

I am wondering how to load multiple .json files in to template.
In my example I have submissions from users and I do not want to store everything in one json file if possible.
How to grab some data from multiple json files?
here is my plunk example
I want to load users.json as well
var app = angular.module('myApp', []);
app.directive('contentItem', function ($compile,$parse) {
templates = {
image: 'image.html',
event: 'event.html',
article: 'article.html',
ad: 'ad.html',
discount: 'discount.html',
video: 'video.html'
}
var linker = function(scope, element, attrs) {
scope.setUrl = function(){
return templates[scope.content.content_type];
}
}
return {
restrict: "E",
replace: true,
link: linker,
scope: {
content: '='
},
templateUrl: 'main.html'
};
});
function ContentCtrl($scope, $http) {
"use strict";
$scope.url = 'content.json';
$scope.content = [];
$scope.fetchContent = function() {
$http.get($scope.url).then(function(result){
$scope.content = result.data;
});
}
$scope.fetchContent();
}
Help appreciated
You can request for JSON either from the controller like:
app.controller('myController', function($scope, $http){
$scope.users = [];
$scope.getUsers = function() {
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).
success(function(data, status) {
$scope.users = data;
}).
error(function(data, status) {
console.log(data || "Request failed");
});
};
and the other approach (better one) would be to make use of angular factory to fetch the JSON file.
myApp.factory('getUsersFactory',['$http',function($http){
return {
getUsers: function(callback){
$http({method: 'JSONP', url: "users.json?query=?callback=JSON_CALLBACK&query="+ $scope.searchString}).success(callback);
}
}
}]);
where now you can include this factory as a dependency and get the user data and assign that in the callback function.

AngularJS 1.2.7 IE8 resource bug

Sample code available here & here. Since Plunker doesn't support IE8 or IE9 very well, the example code can be run by opening the Plunker example in a modern web browser and then launching the Run pane in a separate window and opening that URL in IE8 or IE9.
When making a RESTful call using $resource.query or $resource.get, the promise fails to return any results on IE8 or IE9 if a custom action is defined and used:
factory('ResourceService2', ['$resource', '$q', function($resource, $q) {
var factory = {
query: function() {
var deferred = $q.defer();
$resource('data.json', {'cacheSlayer' : new Date().getTime()}, {
'query': {
method: 'GET',
responseType: 'json',
isArray: true
}}).query(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
};
return factory;
}]).
query():
ResourceService2.query().then(function (response) {
$scope.resource2Rows = response;
});
However, this same call successfully returns results when a custom action is not defined or used:
factory('ResourceService', ['$resource', '$q', function($resource, $q) {
var factory = {
query: function() {
var deferred = $q.defer();
$resource('data.json', {
'cacheSlayer' : new Date().getTime()
}, {}).query(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
};
return factory;
}]).
query():
ResourceService.query().then(function (response) {
$scope.resourceRows = response;
});
Using $http is also successful:
factory('HttpService', ['$http', '$q', function($http, $q) {
var factory = {
query: function() {
var deferred = $q.defer();
$http.get('data.json', {
params: {
'cacheSlayer' : new Date().getTime()
}}).success(function (data) {
deferred.resolve(data);
});
return deferred.promise;
}
};
return factory;
}]).
get():
HttpService.query().then(function (response) {
$scope.httpRows = response;
});
Is this a bug in IE8/IE9? What additional parameters for a custom action must be defined for IE8/IE9 compatibility? The Angular Developer's Guide makes no mention of this problem as of 1.2.7.
CORS is not implemented fully in ie8/9 so this is most likely your issue. Here is the msdn article about it:
http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx