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"));
}});
Related
In my index.js file I have the following POST...
router.route('/bears')
// create a bear (accessed at POST http://localhost:8080/api/bears)
.post(function(req, res) {
var bear = new Bear(); // create a new instance of the Bear model
bear.name = req.body.name; // set the bears name (comes from the request)
// save the bear and check for errors
bear.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Bear created!' });
});
})
.get(function(req, res) {
Bear.find(function(err, bears) {
if (err)
res.send(err);
res.json(bears);
});
});
I test the url http://localhost:8080/api/bears with a POST request on Postman and it was successful. Now I'd like to test my POST request using angular $resource.
I tried the following which I got from the documentation...
app.factory('Profile', function ($resource) {
var Bear = $resource('http://XXX.XXX.X.XX:3000/api/bears/:bearId', {bearId:'#id'});
var single_bear = Bear.post({bearId:123}, function(){
single_bear.name = "Yogi";
single_bear.$save();
});
});
I'm not sure what I should for bearId, I just put a random number. And I am trying to save the bear's name as Yogi. I'm assuming this POST request will occur when I run the app, but I do so and then check to see if my db was filled and there is no entry.
What am I doing wrong?
EDIT
in case you're wondering what a bear entry looks like...
{
"_id": "57ded2302a5ebc050ce3852d",
"__v": 0,
"name": ""
}
Your resource is configured to look for the id property in the data passed (via '#id') yet your data is passing bearId.
Additionally, the data from your server seems to have an _id property, not id nor bearId.
Also, the resource method you're looking for is save(), not post().
I'd go with this type of resource definition...
$resource('http://XXX.XXX.X.XX:3000/api/bears/:id', {id:'#_id'});
Then, you can use it to create a new Bear via
Bear.save({_id: 123, name: 'Yogi'})
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)
}
I am trying to get the data from a JSONP proxy in sencha touch 2.3(I am using sencha architect 3 to develop). I was successfully able to place jsonp call and get the data back. But I am not getting how to separate every single element of json response. Here is my json Response:-
{"data":[{ "PLANTNUM": "1557", "ROUTEID": "90625", "DELIVERYDATE": "2014-02-12T00:00:00-06:00", "MESCOD": "15", "MESFCT": "DLV", "ORIGID": "HH", "JMSTIME": "02/11/2014 00:11:21", }],"success" : true}
Here is my function
success: function(response){
console.log(response);
var temp=response.data.PLANTNUM;
console.log(temp);
}
I can see below in my console:-
Here is my jsonP request
Ext.data.JsonP.request({
url: 'http://localhost:12608',
callbackKey: 'cbfn',
params: {
method: 'sapout',
type: 'sap',
ordnum: '1034986850'
}
I tried using response.PLANTNUM but that is also not working. It always shows undefined
Can anyone help me out here.
Thanks
data is an array, so you want response.data[0].PLATINUM.
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);
};
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