unable to fetch data from json API wordpress throught AngularJS + Onsen - json

I am trying to get data from json API, i am using onsen-ui for creating phonegap app. I am using wordpress plugin to get that.
Here is how i am trying to do this.
module.factory('$data', function($http) {
var data = {};
$http.get('http://www.foduu.com/api/get_recent_posts').
success(function(data, status, headers, config) {
console.log(data.posts);
// return data;
}).
error(function(data, status, headers, config) {
console.log("error in fetching data");
});
});
But this is what i am getting in the console.log.
In HTML i have coded similar to
<ons-list ng-controller="MasterController">
<ons-list-item modifier="chevron" class="item" ng-repeat="item in items" ng-click="showDetail($index)">
<ons-row>
<ons-col width="60px">
<div class="item-thum"></div>
</ons-col>
<ons-col>
<header>
<span class="item-title">{{item.title}}</span>
<span class="item-label">{{item.label}}</span>
</header>
<p class="item-desc">{{item.desc}}</p>
</ons-col>
</ons-row>
</ons-list-item>
</ons-list>
Any suggestions on this will be really helpful.
Thank you

I think you are just missing a return:
module.factory('$data', function($http) {
var data = {};
$http.get('http://www.foduu.com/api/get_recent_posts').
success(function(data, status, headers, config) {
console.log(data.posts);
// return data;
}).
error(function(data, status, headers, config) {
console.log("error in fetching data");
});
return data;
});
As a side note, I suggest that you don't name your own services and factories with a $ prefix. This is an Angular convention for its own provided services.
Also, at the moment, this factory doesn't do much. You should probably return the promise that $http.get returns you:
module.factory('$data', function($http) {
var data = {
getRecentPosts: function() {
return $http.get('http://www.foduu.com/api/get_recent_posts');
}
};
return data;
});
Then handle the promise success and error in the controller that references this factory.

Your factory name should not begin with a $.
Here is an example of a factory that works for me
angular.module('appName')
.factory('FactoryName', function ($http, $q) {
return {
myFunctionName: function (callback) {
var cb = callback || angular.noop;
var deferred = $q.defer();
$http.get('insertYourURLHere')
.success(function (data) {
deferred.resolve(data);
return cb();
}).
error(function (err) {
deferred.reject(err);
return cb(err);
}.bind(this));
return deferred.promise;
},
};
});
Then you can call this in your controller:
$scope.variableName = FactoryName.getProjects()
.then(function(data){
$scope.variableName = data;
})
.catch(function(err){
$log.error(err);
});
Make sure you inject the FactoryName dependency in your controller.

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

Ionic Framework giving error while displaying json data

I am using Ionic Framework and WP-API to develop a mobile app for my Woocommerce based website.I am using the following URL to retriece JSON data about my products from the website -
http://example.com/wp-json/posts?type=product&?_jsonp=JSON_CALLBACK
When I try this URL from my browser, I get a perfect JSON response, with all the required details about my products. However, when i try calling the same URL through Ionic, the framework throughs an error.
UPDATE
$http.jsonp( postsApi ).
success(function(data, status, headers, config) {
$scope.posts = data;
console.log( data );
}).
error(function(data, status, headers, config) {
console.log( 'Post load error.' );
});
Please provide a working link to try it again.
Try using service:
app = angular.module('appName', ['ionic']);
app.factory('postService', function($http){
return {
all: function all() {
var url = 'http://example.com/wp-json/posts?type=product&?_jsonp=JSON_CALLBACK';
return $http.jsonp(url, {cache: true})
.success(function(data){
return data;
}).error(function() {
alert("Error");
});
}
}
});
app.controller("ItemController", function($scope,postService){
$scope.item = [];
postService.all().then(function(data){
data = data.data;
if(data.length == 0){
console.log('empty return');
}else{
$scope.item = data;
}
});
});

How to use HTTP.GET in AngularJS correctly? (Dynamically)

I create it has a service, and then pass it to my controller, The problem is that i have it to read a static file only (1.json), and now that i have populated this folder with more than one json, i would like to know, how can I bring them all in, and make this call dynamically.
Service:
todoApp.factory('eventData', function($http, $q){
return {
getEvent: function(){
var deferred = $q.defer();
$http({method: 'GET', url: '/data/phonebook/1'}).
success(function (data, status, headers, config){
deferred.resolve(data);
}).
error(function (data, status, headers, config){
deferred.reject(status);
});
return deferred.promise;
}
};
});
Controller:
todoApp.controller('FeederController',
function FeederController($scope, eventData) {
eventData.getEvent().then(
function(event){$scope.event = event;},
function(statusCode) {console.log(statusCode)});
}
);
Best Wishes
You'll want to parameterize your service call. Once there you can just change your code to handle 1=>N calls rather than one using a loop.
todoApp.factory('eventData', function($http, $q){
return {
getEvent: function(id){
var deferred = $q.defer();
$http({method: 'GET', url: '/data/phonebook/'+id}).
success(function (data, status, headers, config){
deferred.resolve(data);
}).
error(function (data, status, headers, config){
deferred.reject(status);
});
return deferred.promise;
}
};
});
and your controller becomes
todoApp.controller('FeederController',
function FeederController($scope, eventData) {
$scope.events = [];
for(var i=0; i<10; i++){
eventData.getEvent(i).then(
function(event){$scope.events.push(event);},
function(statusCode) {console.log(statusCode)});
}
}
);
It is good to keep consistent when using .then() vs. .success(). Also, you can use the $http.get() method.
todoApp.factory('eventData', function($http, $q){
return {
getEvent: function(id){
var deferred = $q.defer();
$http.get('/data/phonebook/' + id).then(function(data) {
deferred.resolve(data);
}, function (data, status) {
deferred.reject(status);
});
return deferred.promise;
}
};
});
Then you can get the id of your choice by passing in the id you need.
todoApp.controller('FeederController',
function FeederController($scope, eventData) {
$scope.GetEvent = function(id) {
eventData.getEvent(id).then(function(event){
$scope.event = event;
}, function(statusCode) {
console.log(statusCode);
});
};
});
Then get the info how ever you want.

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

Using return $q.when in Hot Towel Angular datacontext

I've created a web application using the Hot Towel Angular template, and I want to add a service function to the 'datacontext'.
Code is:
(function () {
'use strict';
var serviceId = 'datacontext';
angular.module('app').factory(serviceId, ['common', '$http', datacontext]);
function datacontext(common, $http) {
var $q = common.$q;
var service = {
getFunctions: getFunctions
};
return service;
function getFunctions() {
var f = [];
$http({
method: 'GET',
url: 'https://api.github.com/users/google/repos',
contentType: 'application/json; charset=utf-8'
})
.success(function (data, status, headers, config) {
f = data;
console.log('f=*' + f + '*');
})
.error(function (data, status, headers, config) {
alert('error!');
});
return $q.when(f);
}
}
})();
I see that the console shows some objects:
f=*[object Object],[object Object],[object O...
But when using this in my functionController.js file :
function getFunctions() {
return datacontext.getFunctions().then(function (data) {
console.log('data=*' + data + '*');
return vm.functions = data;
});
}
The value for data is set to undefined.
I'm missing something, please help identify the error.
Solution:
The getFunctions function in the datacontext should return the $http promise object, like this:
function getFunctions() {
return $http.get('https://api.github.com/users/google/repos')
.error(function (data, status, headers, config) {
alert('error ! : ' + status);
});
}
And in the controller, you can use the returned json object as follows:
function getRepos() {
return datacontext.getRepos().then(function (httpResult) {
vm.repos = httpResult.data;
});
}