AngularJS : Factory JSON Array with HTTP GET - json

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);

Related

How to call jsonp api using $http in angularjs

// this is service where i m calling api
app.factory('users',['$http','$q', function($http , $q) {
return {
getUsers: function() {
var deferred = $q.defer();
var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK';
$http.jsonp(url).success(function (data, status, headers, config) {
console.log(data);
deferred.resolve(data);
}).
error(function (data, status, headers, config) {
//this always gets called
console.log(status);
deferred.reject(status);
});
return deferred.promise;
}
}
}]);
//this is my controller where i calling getUsers();
app.controller('myCtrl', function($scope, users) {
$scope.data = users.getUsers();
})
while calling it gives me error
Uncaught ReferenceError: callback is not defined(anonymous function)
Plz give me proper solution so that i can see me api data in <div>. Thanks in advance
$http already returns a promise. There is no need to form a promise of a promise. Try this:
app.factory('Users', ["$http", function($http){
return {
getUsers: function(url) {
return $http({
url: url,
method: 'JSONP'
});
}
};
}]);
Controller:
app.controller("MyCtrl", ["$scope", "Users", function($scope, Users) {
$scope.data = [];
Users.getUsers('http://www.geognos.com/api/en/countries/info/all.jsonp?callback=JSONP_CALLBACK').then(function(response){
console.log(response.data);
$scope.data = response.data;
}).catch(function(response){
console.log(response.statusText);
});
}]);
Here the scenario is a bit different as you have to declare a $window.callback function.
Code
var app = angular.module("demoApp", []);
app.factory('UserService', ['$http', function ($http, $q) {
var getUsers = function () {
var url = 'http://www.geognos.com/api/en/countries/info/all.jsonp?callback=callback';
return $http.jsonp(url);
};
return {
GetUsers: getUsers
}
}]);
app.controller("demoController",
["$scope", "$window", "UserService",
function ($scope, $window, UserService){
UserService.GetUsers();
$window.callback = function (response) {
$scope.countries = response.Results;
}
}]);
Plunkr: http://plnkr.co/edit/MFVpj1sMqJpcDg3ZwQFb?p=preview

Fetching data from local JSON File in angularjs

I want to fetch data from JSON file which is on my local machine. But I am not able to get the data. It is showing some cross domain error for $http.
Here is my code.
angular.module('myApp',[])
.controller('myCtrl', function ($scope, webtest) {
webtest.fetch().then(function (data) {
$scope.accounttype = data;
})
});
.factory('webtest', function($q, $timeout, $http) {
var Webtest = {
fetch: function(callback) {
return $timeout(function() {
return $http.get('webtest.json')
.then(function(response) {
return response.data;
});
}, 30);
}
};
return Webtest;
});
Anyone please help me how to display data from local JSON file?
Thanks in Advance.
It's very simple like
$http.get('phones/phones.json').then(function(response) {
$scope.phones = response.data;
});
Refer:http://stackoverflow.com/questions/21589340/read-local-file-in-angularjs
Don't you have an error message like "$http: is not defined" ?
I tried with a controller, this is working :
var ngApp = angular.module("ngApp", []);
ngApp.controller('myController', ['$http', function($http){
var thisCtrl = this;
this.getData = function () {
this.route = 'webtest.json';
$http.get(thisCtrl.route)
.success(function(data){
console.log(data);
})
.error(function(data){
console.log("Error getting data from " + thisCtrl.route);
});
}
}]);
If you haven't, use web developer tools (Ctrl+Shift+I in firefox).
If you haven't already done so. Try setting up a crossdomain policy for your application.

retrieve json data using GET in angularjs

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;
});
});

Getting data from multiple json in angular js

How can I get the data from two JSON files, named gridData.json and AddedData.json simultaneously using $http.get function?
PApp.controller('ProjectDataController', function($scope, $http) {
$scope.addProject=function($scope){
};
$scope.getData = function(){
$http.get('AddedProjects.json').success(function(data) {
$scope.ProjectStat = data;
});
$http.get('JSON/gridData.json').success(function(data) {
$scope.ProjectStat = data;
});
};
});
Better is to use two seperate variables on the scope. But if you have your reasons to keep it the same objects. You can merge them like below.
PApp.controller('ProjectDataController', function($scope, $http) {
$scope.ProjectStat = {};
$scope.addProject=function($scope){
};
$scope.getData = function(){
$http.get('AddedProjects.json').success(function(data) {
angular.extend($scope.ProjectStat, data);
});
$http.get('JSON/gridData.json').success(function(data) {
angular.extend($scope.ProjectStat, data);
});
};
});

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.