$resource angular returning undefined with $promise - javascript

I have been stuck on this for quite a while now and cannot figure out why the value is not being returned. I am using Angular $resource to make a GET request to an API.
My $resource factory looks like this:
.factory("Bookings", function ($resource) {
return $resource("www.example/bookings_on_date/:day", {});
})
I have tried to implement promises but am unable to do so correctly.
function getBookings(day){
return Bookings.get({"day": day}).$promise.then(function(data) {
console.log(data.total)
return data.total;
});
}
$scope.todaysBookings = getBookings(TODAY);
$scope.tomorrowsBookings = getBookings(TOMORROW);
When I view either console.log($scope.todaysBookings) or $scope.tomorrowBookings in the console it returns undefined.
I have also tried everything from this jsfiddle but unfortunately have not had any luck.

I think it should be like this:
function getBookings(day) {
return Bookings.get({"day": day}).$promise.then(function(data) {
return data.total;
});
}
getBookings(TODAY).then(function(total) {
$scope.todaysBookings = total;
});
getBookings(TOMORROW).then(function(total) {
$scope.tomorrowsBookings = total;
});
Update: I think next code style could help you to prevent next extending method problems:
function getBookings(args) {
return Bookings.get(args).$promise;
}
getBookings({"day": TODAY}).then(function(data) {
$scope.todaysBookings = data.total;
});
getBookings({"day": TOMORROW}).then(function(data) {
$scope.tomorrowsBookings = data.total;
});
A little advantages here:
Pass object into function could help you easily pass different
arguments into method and arguments are very close to method call (a
little bit easy to read);
Return complete response from function
could help you to process different data (method could replay
different response depends on arguments, but it's not good practise
in this case);
p.s. Otherwise, you could remove function declaration and code like this (to keep it as simple, as possible):
Bookings.get({"day": TODAY}).$promise.then(function(data) {
$scope.todaysBookings = data.total;
});
Bookings.get({"day": TOMORROW}).$promise.then(function(data) {
$scope.tomorrowsBookings = data.total;
});

Related

Why is $rootScope's property undefined?

I have an angular application that implements factory functions to handle some API requests for a global object that is implemented in almost all controllers.
factory.loadCart = function() {
var deferred;
deferred = $q.defer();
httpService.get({
service: 'cocacola',
param1: 'userCart',
guid: sessionStorage.token
}, function(r) {
if (r.error == 0) {
$rootScope.user.cart = r.result;
deferred.resolve(r.result);
} else {
deferred.reject("Error al cargar el carrito.")
}
}, function(errorResult) {
deferred.reject(errorResult);
});
return deferred.promise;
}
In the code I set the value of user.cart property as the result of the request. When I go to another controller that also implements this factory method (in this way)...
CartFactory.loadCart().then(function(response) {
$rootScope.user.cart = response;
$scope.cart = $rootScope.user.cart;
if ($rootScope.user.cart.productos.length == 0) {
$state.go('main.tienda');
} else {
getCards();
$rootScope.showCart = false;
}
}, function(error) {
$scope.loading = false;
$scope.showMe = false;
$state.go('main.tienda');
console.log(error);
});
... and go back to the first controller, the user.cart property is undefined and I can't proceed to execute the other functions that are defined as factory methods since the $rootScope.user.cart property is undefined and required as a parameter to these other functions. Also, the $rootScope.user.cart property gets its value after I refresh the browser (but I can't keep this as a solution), I'm very new to Angular so any help will be really appreciated, this is driving me nuts!
I've always found that $rootScope was somewhat difficult to work with, and something of an antipattern in AngularJS... it's like putting variables on the global scope in vanilla JS.
Is there any reason you wouldn't avoid the whole $rootScope.user.cart issue by just keeping cart in CartFactory and then putting an API in CartFactory to getCart, then return whatever cart is to any interested controller?
where you setting 'user' property on $rootScope? can you please put the whole code and always before reading the nested properties from object, check for undefined, in your case put if($rootScope.user) { // your logic }

Use $timeout to wait service data resolved

I am trying to pass data from directive to controller via service, my service looks like this:
angular
.module('App')
.factory('WizardDataService', WizardDataService);
WizardDataService.$inject = [];
function WizardDataService() {
var wizardFormData = {};
var setWizardData = function (newFormData) {
console.log("wizardFormData: " + JSON.stringify(wizardFormData));
wizardFormData = newFormData;
};
var getWizardData = function () {
return wizardFormData;
};
var resetWizardData = function () {
//To be called when the data stored needs to be discarded
wizardFormData = {};
};
return {
setWizardData: setWizardData,
getWizardData: getWizardData,
resetWizardData: resetWizardData
};
}
But when I try to get data from controller it is not resolved (I think it waits digest loop to finish), So I have to use $timeout function in my controller to wait until it is finished, like this:
$timeout(function(){
//any code in here will automatically have an apply run afterwards
vm.getStoredData = WizardDataService.getWizardData();
$scope.$watchCollection(function () {
console.log("getStoredData callback: " + JSON.stringify(vm.getStoredData));
return vm.getStoredData;
}, function () {
});
}, 300);
Despite of the fact that it works, what I am interested in is, if there is a better way to do this, also if this is bug free and the main question, why we use 300 delay and not 100 (for example) for $timeout and if it always will work (maybe for someone it took more time than 300 to get data from the service).
You can return a promise from your service get method. Then in your controller, you can provide a success method to assign the results. Your service would look like this:
function getWizardData() {
var deferred = $q.defer();
$http.get("/myserver/getWizardData")
.then(function (results) {
deferred.resolve(results.data);
}),
function () {
deferred.reject();
}
return deferred.promise;
}
And in your ng-controller you call your service:
wizardService.getWizardData()
.then(function (results) {
$scope.myData = results;
},
function () { });
No timeouts necessary. If your server is RESTFULL, then use $resource and bind directly.
Use angular.copy to replace the data without changing the object reference.
function WizardDataService() {
var wizardFormData = {};
var setWizardData = function (newFormData) {
console.log("wizardFormData: " + JSON.stringify(wizardFormData));
angular.copy(newFormData, wizardFormData);
};
From the Docs:
angular.copy
Creates a deep copy of source, which should be an object or an array.
If a destination is provided, all of its elements (for arrays) or properties (for objects) are deleted and then all elements/properties from the source are copied to it.
Usage
angular.copy(source, [destination]);
-- AngularJS angular.copy API Reference
This way the object reference remains the same and any clients that have that reference will get updated. There is no need to fetch a new object reference on every update.

Meteor.js Collection empty on Client

Why is it that myCollection.find().fetch() returns an empty array [] even though the call is made within if(data){...}? Doesn't the if statement ensure that the collection has been retrieved before executing the console.log()?
Template.chart.rendered = function() {
var data = myCollection.find().fetch();
if(data) {
console.log(data);
}
$('#chart').render();
}
This returns [] in the browser Javascript console.
You could use count() instead which returns the number of results. data itself would be an empty array, [] which isn't falsey ( [] == true ).
Also don't use fetch() unless you're going to use the raw data for it because its quite taxing. You can loop through it with .forEach if you need to.
var data = myCollection.find();
if(data.count())
console.log(data);
//If you need it for something/Not sure if this is right but just an example
$('#chart').render(data.fetch())
The problem is that you have to wait for data from the server. When you just use Template.name.rendered function it is immediately invoked. You have to use Template.name.helpers function to wait for data from the server. Everything is described in the documentation.
It seems when you "remove autopublish" you have to also subscribe on the client.
if(Meteor.isClient) {
Meteor.startup(function() {
Myvars = new Mongo.Collection("myvars");
Meteor.subscribe('myvars')
});
}
and enable allow and publish on the server
if(Meteor.isServer) {
Meteor.startup(function () {
Myvars = new Mongo.Collection("myvars");
Myvars.allow({
insert: function () {
return true;
},
update: function () {
return true;
},
remove: function () {
return true;
}
});
if (Myvars.find().count() == 0) {
Myvars.insert({myvalue:'annoyed'});
}
Meteor.publish("myvars", function() {
return Myvars.find();
});
});
}
I'm new to this as well. I was just looking to have a global value that all clients could share. Seems like a useful idea (from a beginner's perspective) and a complete oversight on the Meteor teams behalf, it was nowhere clearly documented in this way. I also still have no idea what allow fetch is, that too is completely unclear in the official documentation.
It does, but in javascript you have the following strange behaviour
if ([]){
console.log('Oops it goes inside the if')
} // and it will output this, nontheless it is counter-intuitive
This happens because JS engine casts Boolean([]) to true. You can how different types are casted to Boolean here.
Check if your array is not empty in the beginning.
a = [];
if (a.length){
//do your thing
}

$http promise in angular service

I am having a problem with promises in an angular service. I have a service with a method getArea which is supposed to return the name of a service-area. The service gets the service-areas from the API. When getArea gets the service-areas, it finds the name of the requested area, and should return it. However, my code does not work - I get into an infinite loop. I guess I have misunderstood how to use promises?
SupplierService:
var servicePromise;
var getServices = function(){
if( !servicePromise ){
servicePromise = $http.get('/api/services')
.then(function(res){
return res.data.data;
});
}
return servicePromise;
};
var myService = {
getServices : getServices,
getArea : function(questionnaireId){
getServices().then(function(services){
// ...
return "hello world";
});
}
};
return myService;
Controller:
$scope.supplierService = SupplierService;
View:
<div>
<b>Area:</b> {{ supplierService.getArea(r.questionnaireId) }}
</div
I expect the view to show "Area: hello world", but gets into an infinite loop.
Update 1: I have added getServices as a public function in the service, and can access it from the controller like this:
SupplierService.getServices().then(function(d){
$scope.services = d;
});
Therefore I guess the problem is in the getArea method?
Update 2: I was inspired by this answer https://stackoverflow.com/a/12513509/685352. I want to cache the result.
Update 3: Here is a plunker. If you try accessing supplierService.getArea(100) from the view - the browser will not respond.
Your service should look more like this:
var getServices = function(){
var deferred = $q.deferred();
$http.get('/api/services')
.then(function(res){
deferred.resolve(res.data)
});
return deferred.promise;
};
Notice when you create a deferred you must return the deferred.promise (the actual promise) and then when you're async call returns you must call deferred.resolve or deferred.rejected as appropriate (to trigger the success or error functions respectively)
Minor addition I have a plunkr showing a few ways of getting data from a service into your controllers since this is a common issue for devs coming into Angular
http://plnkr.co/edit/ABQsAxz1bNi34ehmPRsF?p=info
It's not absolute best practices since I tried to keep it as simple as possible, but basically showing three different ways to "share" your data keep in mind some of these methods rely on angular.copy which means the property of the service you store the data on must be an Object or an Array (primitive types won't work since the reference can't be shared).
Here's a rewrite including the function inline:
var myService = {
var dataLoaded = false;
var data = {}; //or = [];
getServices : function(){
var deferred = $q.defer();
if( !dataLoaded ){
$http.get('/api/services').then(function(res){
angular.copy(res.data, myService.data);
deferred.resolve(myService.data);
}, function(err){
deferred.reject("Something bad happened in the request");
});
}
else
{
deferred.resolve(myService.data);
}
return deferred.promise;
}
};
return myService;
To explain, I create a new promise using the $q service which you'll need to inject to the service function. This allows me to either resolve that promise with data I already have or to make the call to the service and resolve that data but in both cases when this is being used it's assumed you will just get a promise back and are therefore dealing with an async operation. If you have multiple data sets to load you can use an object to store the flags instead of a single boolean.
i think if you return the $http callback?
//$http.get('/someUrl').success(successCallback);
var getServices = function(){
return $http.get('/api/services');
};
getServices.success(function(services){
// ...
return "hello world";
});
}

Add methods to a collection returned from an angular resource query

I have a resource that returns an array from a query, like so:
.factory('Books', function($resource){
var Books = $resource('/authors/:authorId/books');
return Books;
})
Is it possible to add prototype methods to the array returned from this query? (Note, not to array.prototype).
For example, I'd like to add methods such as hasBookWithTitle(title) to the collection.
The suggestion from ricick is a good one, but if you want to actually have a method on the array that returns, you will have a harder time doing that. Basically what you need to do is create a bit of a wrapper around $resource and its instances. The problem you run into is this line of code from angular-resource.js:
var value = this instanceof Resource ? this : (action.isArray ? [] : new Resource(data));
This is where the return value from $resource is set up. What happens is "value" is populated and returned while the ajax request is being executed. When the ajax request is completed, the value is returned into "value" above, but by reference (using the angular.copy() method). Each element of the array (for a method like query()) will be an instance of the resource you are operating on.
So a way you could extend this functionality would be something like this (non-tested code, so will probably not work without some adjustments):
var myModule = angular.module('myModule', ['ngResource']);
myModule.factory('Book', function($resource) {
var service = $resource('/authors/:authorId/books'),
origQuery = service.prototype.$query;
service.prototype.$query = function (a1, a2, a3) {
var returnData = origQuery.call(this, a1, a2, a3);
returnData.myCustomMethod = function () {
// Create your custom method here...
return returnData;
}
}
return service;
});
Again, you will have to mess with it a bit, but that's the basic idea.
This is probably a good case for creating a custom service extending resource, and adding utility methods to it, rather than adding methods to the returned values from the default resource service.
var myModule = angular.module('myModule', []);
myModule.factory('Book', function() {
var service = $resource('/authors/:authorId/books');
service.hasBookWithTitle = function(books, title){
//blah blah return true false etc.
}
return service;
});
then
books = Book.list(function(){
//check in the on complete method
var hasBook = Book.hasBookWithTitle(books, 'someTitle');
})
Looking at the code in angular-resource.js (at least for the 1.0.x series) it doesn't appear that you can add in a callback for any sort of default behavior (and this seems like the correct design to me).
If you're just using the value in a single controller, you can pass in a callback whenever you invoke query on the resource:
var books = Book.query(function(data) {
data.hasBookWithTitle = function (title) { ... };
]);
Alternatively, you can create a service which decorates the Books resource, forwards all of the calls to get/query/save/etc., and decorates the array with your method. Example plunk here: http://plnkr.co/edit/NJkPcsuraxesyhxlJ8lg
app.factory("Books",
function ($resource) {
var self = this;
var resource = $resource("sample.json");
return {
get: function(id) { return resource.get(id); },
// implement whatever else you need, save, delete etc.
query: function() {
return resource.query(
function(data) { // success callback
data.hasBookWithTitle = function(title) {
for (var i = 0; i < data.length; i++) {
if (title === data[i].title) {
return true;
}
}
return false;
};
},
function(data, response) { /* optional error callback */}
);
}
};
}
);
Thirdly, and I think this is better but it depends on your requirements, you can just take the functional approach and put the hasBookWithTitle function on your controller, or if the logic needs to be shared, in a utilities service.

Categories

Resources