Ionic Framework giving error while displaying json data - json

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

Related

How to map URL to node.js route

I am using ui-router with Angular and Node.js as my UI server for API calls to another server. Right now, my browser URL (dynamic based on dropdown selections) does not map to the server.
For example, the browser URL is "/home?color=Red&&size=Large" when I send the user inputs to Node. When I copy and paste that URL in another browser window, I want the color and size dropdowns to already be selected as Red and Large, and results from API call based on the selections displayed. How can I accomplish this?
My AngularJS controller code:
$scope.getResults = function() {
$location.search('color', $scope.myColor);
$location.search('size', $scope.mySize);
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};
AngularJS service for the above function:
app.factory('server', ['$http', function($http){
return {
getResults : function(color, size) {
var req = {};
req.color = color;
req.size = size;
return $http({
method: 'GET',
url: 'results',
params : req
});
}
}
}]);
ui-router in Angular:
$stateProvider.state('home', {
url: '/home',
templateUrl: '/home.html',
controller: 'MainCtrl',
reloadOnSearch: false
})
In Node.js, I have my route like this:
app.get("/results", function (req, res) {
var api = 'some api call/' + req.query.color + '/' + req.query.size;
request(api, function (error, response, api) {
if (!error && response.statusCode == 200) {
res.json({
Response: api
});
}
});
});
In your code you wrote query parameters but you need to read them, try this:
$scope.getResults = function() {
$scope.myColor = $location.search().color;
$scope.mySize = $location.search().size;
server.getResults($scope.myColor, $scope.mySize)
.success(function(data) {
results = data;
});
};

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.

AngularJS - store page data

I would like to store my datas with local storage or cookie. The data source is a json and this json has a data limitation (10 data per page). So I implemented a "show more" function, which is loads the other jsons when I click a button.
My problem is that I can't store properly the whole loaded datas. I tried with different techniques, but nothing.
Here is the html:
<div ng-controller="MyCtrl">
<div ng-repeat="item in items">
<p>{{item.title}}</p>
</div>
<button ng-click="getItems()" ng-hide="items.length == 0">show more</button>
</div>
And here is the controller:
app.controller('MyCtrl', function($scope, $http) {
$scope.items = [];
var page = 1;
$scope.getItems = function () {
var url = 'https://differentdomain.com/json&page=' + page++;
$http({method: 'GET', url: url}).
success(function (data, status, headers, config) {
if (status == 200) {
$scope.items = $scope.items.concat(data.results);
// or other way
// $scope.items.push.apply($scope.items, data.results)
} else {
console.error('Error happened while getting list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the list.')
});
};
$scope.getItems();
});
Anybody has idea, how can I store it the loaded datas?
If all you want to know is hot to store data you can just use localStorage.setItem to save data and localStorage.getItem to retrieve those data.
The simplest implementation would be
app.controller('MyCtrl', function($scope, $http) {
//retrieving saved object or init new array
$scope.getItems = function () {
//XXX if page is last one then return;
//current page is basically num of objects divided by page size (10 in this case)
var page = ($scope.items.length / 10) + 1;
var url = 'https://differentdomain.com/json&page=' + page++;
$http({method: 'GET', url: url}).
success(function (data, status, headers, config) {
if (status == 200) {
$scope.items = $scope.items.concat(data.results);
//saving current object
localStorage.setItem('items', JSON.stringify($scope.items));
} else {
console.error('Error happened while getting list.')
}
}).
error(function (data, status, headers, config) {
console.error('Error happened while getting the list.')
});
};
$scope.items = JSON.parse(localStorage.getItem('items')) || [];
if (!$scope.items.length) $scope.getItems();
});
The above should work, I assume it is loading 10 more each time you click the button.
Your question seems to be how can you persist those loaded items between browser sessions. If so my suggestion would be for you to look at:
https://github.com/goodeggs/angular-cached-resource
This abstracts away all the difficult parts such as persistence and cache retrieval to give you a consistent API.

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

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.

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