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

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.

Related

$http.post within a $http.post, return response is not updated directly

I have a function, it has a $http.post for login purpose. If success, another $http.post will call a php file that fetches data from database. The problem is that, when I am trying to load the data from localStorage it returns me null. Why is it so?
$scope.loginUser = function ()
{
var data =
{
username: $scope.loginInfo.username,
password: $scope.loginInfo.password
}
$http.post("endpoints/login.php", data).success(function(response)
{
if(response==="ERROR")
{
//DONT DO ANYTHING
}
else
{
localStorage.setItem("token", JSON.stringify(response));
console.log("loginController: name is this " + localStorage);
fetchDataFunction(data);
$state.go("application");
//$state.go("application", result);
}
}).error(function(error)
{
console.error(error);
});
}
fetchDataFunction = function(data)
{
$http.post("endpoints/fetchData.php", data).success(function(response)
{
localStorage.setItem("data", JSON.stringify(response));
}).error(function(error)
{
console.error(error);
});
}
You can return the $http.post, which will return a promise, and then all your code will work in the correct order:
$scope.loginUser = function () {
login($scope.loginInfo).then(function (response) {
localStorage.setItem("token", JSON.stringify(response));
console.log("loginController: name is this " + localStorage.getItem("token"));
fetchDataFunction(data).then(function () {
localStorage.setItem("data", JSON.stringify(response));
console.log(localStorage.getItem("data"));
$state.go("application");
}).catch(function (error) {
console.error(error);
});
}).catch(function (response) {
console.error(error);
});
};
var login = function (user) {
return post("endpoints/login.php", user);
};
var fetchDataFunction = function (data) {
return post("endpoints/fetchData.php", data);
};
var post = function (url, data) {
var deferred = $q.defer;
$http.post(url, data).then(function (response) {
if (response === "ERROR") {
deferred.reject(response);
}
else {
deferred.resolve(response);
}
}).catch(function (error) {
deferred.reject(error);
});
return deferred;
};
Notes:
You will need to make sure you inject $q into your controller along with $http
You should use localStorage.getItem() when recalling information from the global object
You should use then/catch instead of success/error, as these are now depreciated: https://docs.angularjs.org/api/ng/service/$http

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

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.

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

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