what does Restangular.all() return? - angularjs

Why do we have to use Restangular.all every time before making a request.
var messages= Restangular.all('posts');
var newMessage = {
body: "Hello world"
};
messages.post(newMessage);
When I view 'messages' in console it shows an empty array.
1)What are the properties of 'messages'?
2)Is it an instance of collection.

From the documentation: messages is just a restangular object which points to your messages resource uri on the server.
In order to see the messages you would need to call a method on messages such as getList() this will return a promise which you would then unwrap to find your list of messages.

Related

JSON stored into an array not callable by specific index

I am trying to develop an app for my fantasy baseball league to use for our draft (we some kind of quirky stuff all the major sites don't account for) - I want to pull some player data to use for the app by using MLB's API. I have been able to get the response from MLB, but can't do anything with the data after I get it back. I am trying to store the JSON into an array, and if I console.log the array as a whole, it will give me the entire chunk of data, but if I try to call the specific index value of the 1st item, it comes back as undefined.
let lastName = 'judge';
let getData = new XMLHttpRequest;
let jsonData = [];
function getPlayer () {
getData.open('GET', `http://lookup-service-
prod.mlb.com/json/named.search_player_all.bam?
sport_code='mlb'&active_sw='Y'&name_part='${lastName}%25'`, true)
getData.onload = function() {
if (this.status === 200) {
jsonData.push(JSON.parse(this.responseText));
}
}
getData.send();
console.log(jsonData);
}
When I change the above console.log to console.log(jsonData[0]) it comes back as undefined. If I go to the console and copy the property path, it displays as [""0""] - Either there has to be a better way to use the JSON data or storing it into an array is doing something abnormal that I haven't encountered before.
Thanks!
The jsonData array will be empty after calling getPlayer function because XHR loads data asynchronously.
You need to access the data in onload handler like this (also changed URL to HTTPS to avoid protocol mismatch errors in console):
let lastName = 'judge';
let getData = new XMLHttpRequest;
let jsonData = [];
function getPlayer () {
getData.open('GET', `https://lookup-service-
prod.mlb.com/json/named.search_player_all.bam?
sport_code='mlb'&active_sw='Y'&name_part='${lastName}%25'`, true)
getData.onload = function() {
if (this.status === 200) {
jsonData.push(JSON.parse(this.responseText));
// Now that we have the data...
console.log(jsonData[0]);
}
}
getData.send();
}
First answer from How to force a program to wait until an HTTP request is finished in JavaScript? question:
There is a 3rd parameter to XmlHttpRequest's open(), which aims to
indicate that you want the request to by asynchronous (and so handle
the response through an onreadystatechange handler).
So if you want it to be synchronous (i.e. wait for the answer), just
specify false for this 3rd argument.
So, you need to change last parameter in open function as below:
getData.open('GET', `http://lookup-service-
prod.mlb.com/json/named.search_player_all.bam?
sport_code='mlb'&active_sw='Y'&name_part='${lastName}%25'`, false)
But from other side, you should allow this method to act asynchronously and print response directly in onload function.

Post promise returns ids that are needed for another post promise

I am using http post methods to get the data from an endpoint to populate a table. I first need to get the id of the recipients, and subsequently I need to use the Id of these recipients to grab an object belonging to the recipient from another endpoint.
I have a http post that returns a promise. Using .then, I store these id numbers which I store on a javascript array. I then need to make one http post for each id on the array that will return another promise. Not sure if this is the best way to go:
getRecipients = httpService.doPost("/search", [], {userId:"test"});
getRecipients.then(function(recipientData){
vm.recipients = recipientData.data.recipients;
}).then(function(){
for(x in vm.recipients)
{
httpService.doPost("/searchObjects", [], vm.recipients[x].id)
.then(function(){
//store each object returned on another array here....
});
}
});
NOTE: doPost(endpoint, not used, parameters to do the search)
With the above method, the problem is that the for loop will not wait for the then and will move to the next iteration once the doPost has been called.
I guess I can use bluebird, but not sure if that would be the best way to go in here, and if so, how should it be done (note that this is server side javascript so require is not available per say unless I use require.js)?
If I'm understanding you correctly, you're looking for something like this:
getRecipients = httpService.doPost("/search", [], {userId:"test"});
getRecipients.then(function(recipientData){
vm.recipients = recipientData.data.recipients;
var promises = [];
for (x in vm.recipients) {
promises.push(httpService.doPost("/searchObjects", [], vm.recipients[x].id));
}
// in this case $q.all waits for all of the requests to finish
// then gives the responses
$q.all(promises).then(function(responses) {
// responses is an array of the responses
// from each request in the promise array
});
});

Restangular getList() does not return array of list items

I try to use Restangular to handle calls to my restful API.
Here is my code:
var baseStories = Restangular.all('stories/all');
baseStories.getList().then(function (stories) {
console.log(stories);
})
The console.log shows the full restangularized array instead of an array of stories as I'd expect.
I use the RestangularProvider.addResponseInterceptor from the docs to unwrap the response data.
Has anyone an idea what I'm missing?
Edit:
Below is a screenshot of the console.log output from the code above. I see two stories (which is correct) and a bunch of Restangular methods. Is it possible to only get the stories?
Actually addResponseInterceptor must return restangularized element. It is written in the documentation:
https://github.com/mgonto/restangular#addresponseinterceptor
In order to get clean response you have to call plain() method on the response element:
var baseStories = Restangular.all('stories/all');
baseStories.getList().then(function (response) {
$scope.stories = response.plain();
})

TVRage consume service via AngularJS

i am trying to consume this webservice (http://services.tvrage.com/feeds/show_list.php) from TVRage using Angularjs.
I can 'connect' to the service (using firebug I see GET show_list.php STATUS 200 OK) but when i try to print any data from the response I get none.
This is the code that i use:
var TV_Episodes = angular.module('TV_Episodes', ['ngResource']);
TV_Episodes.controller('GetAllEpisodes', function($scope, $resource) {
var dataService = $resource('http://services.tvrage.com/feeds/show_list.php');
$scope.data = dataService.get();
console.log($scope.data());
});
any ideas on how I can just console.log the the response?
UPDATE 1:
After some more trying i found out that that i get the following error as a response from TVRAGE.
"XMLHttpRequest cannot load http://services.tvrage.com/feeds/show_list.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access."
therefor i tweaked my code so
var dataService = $resource('http://services.tvrage.com/feeds/show_list.php?key=xxxx',{},{headers: { 'Access-Control-Allow-Origin': '*' }});
but i still get the same error as before.
$resource.get() returns a promise, which means you are likely printing to the console prior to the data being retrieved. Instead use the appropriate callback function:
$scope.data = dataService.get(function() { console.log($scope.data); });
The get method is asyncronous. When it is called it returns immediately with a reference to an object (or array, if specified - but not a promise as indicated in MWay's answer). Then, later, that same reference is updated with the data that is returned from the server on success. Here's the relevant part from the documentation:
It is important to realize that invoking a $resource object method immediately returns an empty reference (object or array depending on isArray). Once the data is returned from the server the existing reference is populated with the actual data. This is a useful trick since usually the resource is assigned to a model which is then rendered by the view. Having an empty object results in no rendering, once the data arrives from the server then the object is populated with the data and the view automatically re-renders itself showing the new data. This means that in most cases one never has to write a callback function for the action methods.
As fast as the request might be, it won't resolve until the event loop comes around again. The resource is helpfully designed to free you up from having to worry about writing callbacks. If you need to though, the get method takes callback function parameters that will be invoked when the request resolves and the data is ready.
var TV_Episodes = angular.module('TV_Episodes', ['ngResource']);
TV_Episodes.controller('GetAllEpisodes', function($scope, $resource) {
var dataService = $resource('http://services.tvrage.com/feeds/show_list.php');
$scope.data = dataService.get(function () {
console.log($scope.data());
});
});
Or, you can access the promise used for processing the request by using *$promise", which is a property on empty instance object returned from get.

BackboneJS model.fetch() unsuccessful

Hi I have this model :
window.shop = Backbone.Model.extend({
initialize: function () {
console.log('initializing shop');
},
urlRoot: "shopData.json",
});
and then i go :
var myShop = new shop();
myShop.fetch({
success: function (model, resp){
console.log(resp);
},
error: function (model, resp){
console.log("error retrieving model");
}}, {wait: true});
now I'm always getting the error message - never reaching success :-(
thanks for any help.
Edit 1:
As per your comment the server is sending the proper response but Backbone is still calling the error function. Add the following line at the beginning of the error callback:
error: function (model, resp){
console.log('error arguments: ', arguments);
console.log("error retrieving model");
}
The first line should print an array of objects. The first element in the array should the jqXhr object, the second should be a string representation of the error. If you click on the first object, the dev tools will let you inspect its properties. Read up on the properties of the object here http://api.jquery.com/jQuery.ajax/#jqXHR.
Using that information you can verify if the jQuery is receiving an error from the server.
If there is no server side error, then check the value of the responseText property. That holds the string data returned from the server. $.ajax will try to parse that data into JSON. Most likely the parsing is throwing an error and the error handler is being raised instead.
Copy the response text and paste it into http://jsonlint.com/. Verify that the response sent from the server is valid JSON. Do update your question with the output of the console.log statement and the responseText property of the jqxhr object.
-x-x-x-
You seem to be using the model independently. As the per the documentation, http://backbonejs.org/#Model-url,
Generates URLs of the form: "/[urlRoot]/id"
That means, you are making a request to shopData.json/id. Also, you haven't specified the id.
Insert a console.log(myShop.url()) before the myShop.fetch(). Let us know whats the output. Also, possibly share the details of the ajax request as seen in Firebug or Chrome Dev Tools. I am interested in two things, the request url and the response returned by the server. (http://getfirebug.com/network)

Resources