how can i handle a jsonp response? i tried to search but i cant solve it. the screen shot below shows a jsonp result.1
i get that jsonp response using this code, services.js
var app=angular.module('F1FeederApp.services', []);
app.config(function($sceDelegateProvider) {
$sceDelegateProvider.resourceUrlWhitelist([
'self',
'http://ergast.com/**'
]);
});
app.factory('ergastAPIservice', function($http) {
var ergastAPI = {};
var urlFiltered = 'http://ergast.com/api/f1/current/driverStandings.json';
ergastAPI.getDrivers = function() {
return $http({
method: 'JSONP',
url: urlFiltered
});
}
return ergastAPI;
});
now, i access it using the code below and gives me result on the 1st picture.
angular.module('F1FeederApp.controllers', []).
controller('driversController', function($scope, ergastAPIservice) {
$scope.nameFilter = null;
$scope.driversList = [];
// //ergastAPIservice.getDrivers() ->> when i try this i get error this is not a function.
//ergastAPIservice.getDrivers().success(function (response) {
//Dig into the responde to get the relevant data
// $scope.driversList = response.MRData.StandingsTable.StandingsLists[0].DriverStandings;
//});
//code above doesnt work so i tried to access it or atleast show a value like
// the code below
console.log(ergastAPIservice.getDrivers());
console.log(ergastAPIservice.getDrivers().MRData.StandingsTable.StandingsLists[0].DriverStandings);
});
now i get the 1st picture using console.log(jsonp response).
how can i get the list of drivers in that response?,
like: collectionVar = response.getDrivers();.
any link or same problem links would help thanks!
Do something like this. This should work . You are getting a promise . Promises are handled like below. Learn more about promise
app.controller("testController", function($scope,testService){
testService.getDrivers ()
.then(function (response) {
$scope.standingTable = response.data.MRData.StandingsTable.StandingsLists[0].DriverStandings;
// handle valid reponse
},
function(error) {
//handel error
});
}
Big thanks for Noman! i didnt know that i was getting a angular promise response at first. though i want to get the driver standing list. so i use this code.
$scope.driversList = response.data.MRData.StandingsTable.StandingsLists[0].DriverStandings;
Related
i am trying to get response of post/get requests , getting response successfully inside post/get,but unable to get result out of post/get .
when i print on console it is showing "undefined". any suggestions , here is my code
index.html:
<div ng-app="myApp" ng-controller="customersCtrl">{{ponies}}</div>
Angular code:
var myApp = angular.module('myApp', []);
angular service:
myApp.factory('ponyService', function($http) {
var getPonies = function() {
return $http.get('https://www.w3schools.com/angular/customers.php');
};
return {
getPonies: getPonies
};
});
myApp.controller('customersCtrl', function($scope, ponyService) {
ponyService.getPonies().success(function(data) {
$scope.ponies = data;
});
console.log($scope.ponies); // here want to print data because want to use whole controller
});
That's because posts and gets are asynchronous.
Your console.log won't wait for the response.
Put your console inside success in order check it's data.
Try like this
ponyService.getPonies().success(function(data) {
$scope.ponies = data;
console.log($scope.ponies);
});
or you can watch it's changes (but it's not recommended just for test purposes),
Like this
ponyService.getPonies().success(function(data) {
$scope.ponies = data;
});
$scope.$watch("ponies",function(val){
if(val)
console.log(val)
})
It is because a $http returns a promise (async request) so if you did something like this
ponyService.getPonies().success(function(data) {
$scope.ponies = data;
});
console.log($scope.ponies);
it will log undefined, as you are trying to log it before the request is finished.So you need to chain to that promise in any code that needs to access the resolved data.Like:
ponyService.getPonies().success(function(data) {
$scope.ponies = data;
console.log($scope.ponies);
/* access data or $scope.ponies in here */
});
or you can use promise like
ponyService.getPonies().then(function (data) {
$scope.ponies = data;
console.log($scope.ponies);
/* access data or $scope.data in here */
});
I had been using a angular service in which the data was returning just fine.
However, I wanted to instead call directly to the json file except now it doesn't like the data.
Working version
Controller code:
var confirm = this;
confirm.booking = airConfirmationService.getTestData();
Service code :
.factory('airConfirmationService', airConfirmationService);
var confirm = {};
confirmed.getTestData = function () {
return {
"flightData": [
{
"MultiCarrier": false,
// etc...
However I am switched to a service with .service and calling the location of the .json file up directly.
Not working ( well, it pulls the data but returns in a way that I don't understand)
.service('airConfirmationService', function ($http) {
this.getTestData = function () {
return $http({
url: '../apps/temp/Api_Responses/confirm.booking.json',
method: "GET"
})
}
});
Then in controller
var confirm = this;
confirm.booking = airConfirmationService.getTestData();
console.log(confirm.booking) // Picture attached shows how the data looks
// My attempt at getting "at" the data ...
//var temp = [];
//temp = airConfirmationService.getTestData();
//confirm.booking = temp.d.Data;
UPDATE
While this code below "works" I have a feeling that not doing "q" /defer / .then will be bad...
This code works in the controller calling the service, but how can i add/change to have q/defer and/or .then ?
var getData = airConfirmationService.getTestData();
getData.success(function(data) {
confirm.booking = data;
});
Angular $http is Asynchronous. The network operation to get the data from the server may take some time, so angular does not expect your app to wait until the operation is complete, stuck hung until the data is available. Therefore, a promise object is used as a placeholder for the data. Promises have a .then() function which tells the promise that it should execute some other code after the operation is complete. They also provide a .catch() function for when something goes wrong and the data isn't returned.
The correct way to use $http is:
var confirm = this;
confirm.testData = {};
airConfirmationService.getTestData()
.then(function(response) {
confirm.testData = response.data;
})
.catch(function(){
//something went wrong
});
I try to get some important things like: companyid,employeeid etc. with every request that a user makes. So this has to be received before everything else is done.
After that the user receives information based on his companyid that he sets with every request (get/company/{companyid}).
The problem that I have is that the response for receiving the companyid takes to long and angular already tries to make a request to (get/company/{companyid}) obviously there is no companyid yet.
I've tried to fix this whit promise but it's not working.
Here I try to receive some important information about the user(that I do with every request) :
Service
(function () {
angular.module('employeeApp')
.service('authenticationservice', authenticationservice);
function authenticationservice($http,$location,authenticationFactory,$q,GLOBALS,$cookies) {
this.validateUser = function () {
var vm = this;
vm.deferred = $q.defer();
data = {"api_token": api_token};
return $http.post(GLOBALS.url+'show/employee/' + $cookies.get('employeeid'),data)
.success(function(response)
{
vm.deferred.resolve(response);
})
.error(function(err,response)
{
vm.deferred.reject(err);
});
return vm.deferred.promise;
}
}
})();
Routes file
(In my routes file I use the authenticationservice to set all important users variables.)
employeeAppModule.run([
'authenticationservice',
'constants',
function(authenticationservice,constants) {
authenticationservice.validateUser()
.then(function(response)
{
constants.companyid = response.result.Employee;
constants.role = response.result.Role;
constants.name = response.result.FirstName;
console.log('test');
},
function(response){
console.log('error');
});
}
]);
So the problem is that the user information is set to late and angular already goes to my homeController where he uses the companyId that is not being set yet.
Thankyou
The problem in your current code is return $http.post are having two return statement in your validateUser method. Which is returning $http.get before returning return vm.deferred.promise; & that why customly created promise doesn't get returned from your method. Though by removing first return from $http.get will fix your problem, I'd not suggest to go for such fix, because it is considered as bad pattern to implement.
Rather I'd say, you should utilize promise return by $http method, & use .then to return data to chain promise mechanism.
Code
function authenticationservice($http, $location, authenticationFactory, $q, GLOBALS, $cookies) {
this.validateUser = function() {
var vm = this;
data = {
"api_token": api_token
};
return $http.post(GLOBALS.url + 'show/employee/' + $cookies.get('employeeid'), data)
.then(function(response) {
var data = response.data;
retrun data;
}, function(err) {
return $q.reject(err);
});
}
}
To make sure that $ http return a $ promise object you need to check that the action in the controller returns a value and it is not a void action.
I am new to Angular, and am trying to get up to speed with ngResource.
I created a factory in my chapter.service.js file
angular.module('myApp')
.factory('Chapter', function ($resource) {
return $resource('/api/book/chapter/:id'); // Note the full endpoint address
});
matchescontroller.js
angular.module('myApp').controller('matchesCtrl', function($scope, $location, Chapter) {
// This is used to get URL parameters
$scope.url = $location.path();
$scope.paths = $scope.url.split('/');
$scope.id = $scope.paths[2];
$scope.action = $scope.paths[3];
//Trying to call the test data
var chapters = Chapter.query();
$scope.myFunction = function() {
alert(chapters.length);
}
My view where I test the function
<button ng-click="myFunction()">Click Here</button>
I created a test function to test whether my query returned any results. When I click on the button, I'm alerted with 0, which means the query didn't work.
When I change the function to
$scope.myFunction = function() {
console.log(Object.keys(chapters));
}
I get [$promise, $resolve], but none of the Schema keys
I must be doing something wrong, but I was looking at this tutorial
http://www.masnun.com/2013/08/28/rest-access-in-angularjs-using-ngresource.html
Any help will be appreciated.
Edit: Here is the response I got from the server
GET http://localhost:9000/api/book/chapter/1 500 (Internal Server Error)
$scope.myFunction = function() {
Chapter.query({}, function(data) {
$scope.chapters = data;
}, function(error) {
// custom error code
});
}
When working with $resource I prefer to use the success/error handlers that the API comes with as opposed to dealing the promise directly. The important thing to realize is that just because you called query does not mean that the result is immediately available. Thus the use of a callback that handles success/error depending on what your backend returns. Only then can you bind and update the reuslt in the UI.
Also, while we're talking about it I notice that you didn't wire up the optional paramter in your $resouce URL. $resource takes a second paramter which is an object that supplies mapping for the /:id part of your route.
return $resource('/api/book/chapter/:id', {id: '#id'});
What this notation means is that you pass an object to $resource that has a property called id, it will be subbed into your URL.
So this:
$scope.item = {id: 42, someProp: "something"};
Chapter.get({$scope.item}....
Will result in an API call that looks like '/api/book/chapter/42'
You get a promise from $resource and not the "result" from your database. The result is inside the promise. So try this
var chapters = Chapter.query();
$scope.myFunction = function() {
chapters.then(function(data) {
console.log(data);
});
}
I must admit, that I am not thaaaaat familiar with ngResource, so Jessie Carters is right, the correct syntax is:
chapters.get({...}, function callback() {...})
I am trying to read data from json and wait until data will be fetched into $scope.urls.content. So I write code:
$scope.urls = { content:null};
$http.get('mock/plane_urls.json').success(function(thisData) {
$scope.urls.content = thisData;
});
And now I am trying to write something like callback but that doesn't work. How can i do that? Or is there any function for this? I am running out of ideas ;/
Do you mean that ?
$http.get('mock/plane_urls.json').success(function(thisData) {
$scope.urls.content = thisData;
$scope.yourCallback();
});
$scope.yourCallback = function() {
// your code
};
You want to work with promises and $resource.
As $http itself returns a promise, all you got to do is to chain to its return. Simple as that:
var promise = $http.get('mock/plane_urls.json').then(function(thisData) {
$scope.urls.content = thisData;
return 'something';
});
// somewhere else in the code
promise.then(function(data) {
// receives the data returned from the http handler
console.log(data === "something");
});
I made a pretty simple fiddle here.
But if you need to constantly call this info, you should expose it through a service, so anyone can grab its result and process it. i.e.:
service('dataService', function($http) {
var requestPromise = $http.get('mock/plane_urls.json').then(function(d) {
return d.data;
});
this.getPlanesURL = function() {
return requestPromise;
};
});
// and anywhere in code where you need this info
dataService.getPlanesURL().then(function(planes) {
// do somehting with planes URL
$scope.urls.content = planes;
});
Just an important note. This service I mocked will cache and always return the same data. If what you need is to call this JSON many times, then you should go with $resource.