AngularJS Chaining $http calls - angularjs

I am still quite new to AngularJS and struggling to figure the following out.
I have quite a few web-services that I need to use, quite a few of them relies on the data from another to successfully make the next call.
For example, the first web-service will retrieve a list of Profiles.
ip.controller("ProfilesCtrl", function($scope, $http) {
$http.post("Profile_List.asp").success(function(data) {
$scope.profiles = data;
}).error(function() {
alert("An unexpoected error ocurred while loading profiles!");
});
});
Profiles returns a JSON object.
Data returned:
{
"Success": true,
"ErrorMessage": "",
"Objects": [{
"GUID": "208FF69D-A4EB-4760-B2ED-414C900F4AAC",
"Name": "John Doe",
"Status": false
}, {
"GUID": "BC5C53FD-5CA7-4DBE-8594-D26AD88B758B",
"Name": "Jane Doe",
"Status": true
}, {
"GUID": "2FCD677B-DA36-4014-823A-9BDD1A72AD66",
"Name": "Anonymous",
"Status": true
}]
}
Ok, so after I have made the initial call, I need to send the GUID of each Profile Object to another web-service. This service will use the GUID to determine the ID of that specific Profile.
The data from the second web-service will only return the ID for the GUID of the first call.
How can I chain these $http calls? Would it be better to create a new json object and use data from there?
I have done this before using ajax.
*Another question regarding my controller code, is this fine like this or would it be better to maybe do the $http calls as a Service, Provider or Factory? How can I go about doing this?
Any help/links with getting the above to AngularJS code would be appreciated.
Please ask if anything is unclear.

Simply call execute the next call in your "success" handler.
$http.post("Profile_List.asp").success(function(data) {
$scope.profiles = data;
//first call succeeded, and we have the data. call method 2
executeStep2($scope.profiles);
})
function executeStep2(profiles)
{
$http.post("second_method") // etc. (you can just send profiles as post data here)
}

Related

need to declare all the error messages globally in a property file

I need to declare all the error message like (401,200 etc....) in a property file, need to access them later where ever its required
in the below format mostly
key=messsage
404 = This request caon't be processed
200 = your request is successfull
Is it posssible in angular ifso could any body give me an idea, thank u
======================================================================
I think ... it is possible. lol !
You can declare global value via JSON file. (keep it on your server)
See the JSON format here.
Example:
globalvalue.json
[
{
"key": 404,
"message": "This request caon't be processed"
},
{
"key": 200,
"message": "your request is successfull"
}
]
And next you just read that global value via your server it store the JSON file.
Angular Code:
angular
.module('app.services', [])
.factory('Friend', function ($http) {
return {
get: function () {
return $http.get('/globalvalue.json');
}
};
});
Then use your factory this way:
.angular
.module('app.controllers', ['app.services'])
.controller('yourCtrl', function ($scope, Friend) {
Friend.get().then(function (msg) {
$scope.msg = msg;
});
});
Cr. Reading data from JSON file in Angularjs.
let's fun. :)

Backbone js. simple error fetching data from the server

I'm new to Backbone, that is why I wrote "simple" in the title, cause this might be an error with a simple solution. I haven't been able to fetch the data from the server and log it.
So, this is the code:
TheModel = Backbone.Model.extend({
urlRoot: '/times/api/day'
});
var nModel = new TheModel({ id:1 });
nModel.fetch();
console.log(nModel.get("minutes"));
The API url is returning a JSON object:
curl http://localhost:7000/times/api/day/1
{"date": "2014-10-25T18:56:32Z", "minutes": 400, "comments": "Tw.Karaoke", "trophy": "", "owner": null}
It doesn't log "400", it logs "undefined", why?.
the fetch operation is asynchronous, so you have to wait till the ajax call is completed
nModel.fetch({
success:function(){
console.log(nModel.get("minutes"));
}});

Module factory is not returning data

I am trying to read JSON reply from server. You can find my code here.
https://github.com/ameyjah/feeder
In firefox firebug, I can see that server has returned JSON reply but when I store that into $scope.variable, I am not able to access that information.
Module code
var res
angular.module('myApp.services', ['ngResource'])
.factory('feedFetcher', ['$resource',
function($resource) {
var actions = {
'sites': {method:'GET', params: { action:"sites"} ,isArray:false},
'feeds': {method:'GET', params: { action:"sites"} ,isArray:false}
}
res = $resource('/api/:action', {}, actions);
return res
}
]);
Controller code
$scope.sites = feedFetcher.sites().sites;
console.log($scope.sites);
Reply seen in firebug:
{
"sites": [
{
"id": 0,
"title": "google"
},
{
"id": 1,
"title": "yahoo"
}
]
}
I think I have messed up the way I should define my factory but I am not able to identify. Any help would be helpful.
When you call sites() it returns an empty object and initiates an AJAX request, which will populate the "sites" property on that object. I think you should use it like this:
$scope.results = feedFetcher.sites();
console.log($scope.results.sites); // will be undefined as AJAX not complete
Then in your html you can use the results and they will be filled in when AJAX completes, or watch for it:
$scope.$watch('results.sites', function() {
// this will be called twice, once initially
// and again whenever it is changed, aka when AJAX completes
console.log($scope.results.sites);
};

Angularjs JSONP not working

I might be missing something here but I can't make this JSONP request work, here is the code:
var url = 'http://' + server + '?callback=JSON_CALLBACK';
$http.jsonp(url)
.success(function(data){
console.log('success');
})
.error(function () {
console.log('error')
});
The request fires ok and I am getting the response (with header Content-Type:application/json) in this format:
[{"id": "1", "name": "John Doe"},
{"id": "2", "name": "Lorem ipsum"},
{"id": "3", "name": "Lorem ipsum"}]
Can you see anything wrong? Maybe the format I should return from the server is not right?
Angular fires the error callback without any error message besides the one I set ('error').
#TheHippo is correct the data should not just be a plain json response. Here is a working example of a JSONP request against a youtube endpoint in AngularJS.
A couple of things to note in this example:
Angular's $http.jsonp converts the request querystring parameter from callback=JSON_CALLBACK to callback=angular.callbacks._0.
When calling the youtube endpoint I needed to specify to the service that this is a JSONP request by using alt=json-in-script instead of alt=json in the querystring. This was found in their documentation.
Compare the results of this url to this one to see the difference between JSON and JSONP response in your browser.
Take a look at the Chrome Network Panel in Developer Tools to help compare and troubleshoot with your request/response.
I know this example is very specific but hopefully it helps!
JSONP requires you do wrap your data into a JavaScript function call. So technically you return a JavaScript file and not a Json file.
The data returned from server should similar to this:
// the name should match the one you add to the url
JSON_CALLBACK([
{"id": "1", "name": "John Doe"},
{"id": "2", "name": "Lorem ipsum"},
{"id": "3", "name": "Lorem ipsum"}
]);
Edit: If some one else stumbles across problems with angular's JSONP please also read this answer to this question, it contains usefull informations about how angular handles the actual callback function.
If the response data is "pure" JSON, we can just handle it with angular's $http.get.
$http.get(url).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
$scope.responseArray = response.data;
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Refer to the example on w3schools

How to create Backbone Collection from a JSON API call that returns root parameters as well as array

Backbone.js noob here.
I want to create a collection, from a JSON API external to my application. Specifically, the api from Stackoverflow. I know I should set the url parameter from a collection like this:
App.Collections.Users = Backbone.Collection.extend({
model: User,
url: "http://api.stackoverflow.com/1.1/users/800271;562692?jsonp=?&key=blahblah"
});
The problem is that the JSON API returns something like:
{
"total": 2,
"users": [
{
"user_id": 800271,
},
{
"user_id": 800272,
}
]
}
}
How do I ignore the "total" attribute?
If this is the only collection in your app to work with such api, all you have to do is to override parse method for it:
App.Collections.Users = Backbone.Collection.extend({
// ...
parse: function(resp, xhr) {
return resp.users
}
})
If you also have to save your models, maybe you will need to override Backbone.sync. Don't hesitate to read backbone's source: it's thoroughly annotated and easy to follow.

Resources