Getting a value from a AngularJS Promise in MeanJS - javascript

I'm playing around with MeanJS recently and I ran into an issue that I'm not well versed in so I'm hoping someone can help here.
I have a angular controller that sets it scope like this:
// Find existing Topic
$scope.findOne = function() {
$scope.topic = Topics.get({
topicId: $stateParams.topicId
});
};
I this sets the topic in the $scope. However, I also need to get a value off of the topic as well. Lets assume it is a date such as createdAt. I need to get this value and then perform another operation on it in order to set another scope value. The problem is, the $scope.topic object is an Angular promise. How can I get the value createdAt (which is a Date) off of that promise?

You can use promise callback.
$scope.findOne = function() {
$scope.topic = Topics.get({
topicId: $stateParams.topicId
});
$scope.topic.$promise.then(function(data) {
// access data.createdAt here
});
};
Its actual also depends on that where you want to use this. So if you want to use this in the view, you can write directly as:
<span> Created at: {{topic.createdAt}}</span>
Angular will autoupdate that scope variable when data is loaded.

Related

Angular Unit tests: Mocking multiple independent promises

This is a long one, so I will begin by asking the question I struggle with:
How do I resolve independent promises for the same function that has been run with different parameters in unit testing, and get different values?
I have difficulties with mocking an environment where multiple http-requests are executed, independent of each other, but with the same service-object.
It works in real application, but setting up a proper mocking environment for unit-testing (Jasmine, Karma) has proven quite difficult.
Let me explain the environment, and what I have tried to to:
First off, I have an Angular Controller that makes a single http-request with a custom service object, and mocking this in the tests works. Then I have made a Controller that makes multiple independent http-requests with the same service object, and I have attempted at expanding my unit testing to cover this one, given my success with the other controller.
Background on how it works in controller with single request/promise:
If you don't want to go through all this, you can jump straight to The real problem: Testing multiple independent requests and promises. You probably should.
Let us first go with the single-request controller and its working test, to have a foundation.
SingleRequestController
function OpenDataController($scope, myHttpService) {
$scope.parameterData = {requestString : "A"};
$scope.executeSingleRequest = function() {
myHttpService.getServiceData($scope.parameterData)
.then(function (response) {
$scope.result = response.data;
});
}
// Assume other methods, that calls on $scope.executeSingleRequest, $scope.parameterData may also change
}
As you probably figure, myHttpService is a custom service that sends a http-request to a set URL, and adds in the parameters passed on by the controller.
SingleRequestControllerTest
describe('SingleRequestController', function() {
var scope, controller, myHttpServiceMock, q, spy;
beforeEach(module('OppgaveregisteretWebApp'));
beforeEach(inject(function ($controller, $q, $rootScope, myHttpService) {
rootScope = $rootScope;
scope = rootScope.$new();
q = $q;
spy = spyOn(myHttpService, 'getServiceData');
// Following are uncommented if request is executed at intialization
//myHttpServiceMock= q.defer();
//spy.and.returnValue(myHttpServiceMock.promise);
controller = $controller('OpenDataController', {
$scope: scope,
httpService: httpService
});
// Following are uncommented if request is executed at intialization
//myHttpServiceMock.resolve({data : "This is a fake response"});
//scope.$digest();
}));
describe('executeSingleRequest()', function () {
it('should update scope.result after running the service and receive response', function () {
// Setup example
scope.parameterdata = {requestString : "A", requestInteger : 64};
// Prepare mocked promises.
myHttpServiceMock= q.defer();
spy.and.returnValue(myHttpServiceMock.promise);
// Execute method
scope.executeSingleRequest();
// Resolve mocked promises
myHttpServiceMock.resolve({data : "This is a fake response"});
scope.$digest();
// Check values
expect(scope.result).toBe("This is a fake response");
});
});
});
This is a light-weight pseudo copy of a real life implementation I'm working with. Suffice to say, I have, through trying and failing, discovered that for each and every call on myHttpService.getServiceData (usually by directly calling $scope.executeSingleRequest, or indirectly through other methods), the following has to be done:
myHttpServiceMock must be initialized anew (myHttpServiceMock= q.defer();),
initialize spy to return mocked promise (spy.and.returnValue(myHttpServiceMock.promise);)
Execute the call to the service
Resolve the promise (myHttpServiceMock.resolve({data : "This is a fake response"});)
Call digest (q.defer();)
So far, it works.
I know it's not the most beautiful code, and for each time the mocked promise has to be initialized and then resolved, a method encapsulating these would be preferable in each test. I've chosen to show it all here for demonstrative purpose.
The real problem: Testing multiple independent requests and promises:
Now, let us say the controller does multiple independent requests to the service, with different parameters. This is the case in a similar controller in my real life application:
MultipleRequestsController
function OpenDataController($scope, myHttpService) {
$scope.resultA = "";
$scope.resultB = "";
$scope.resultC = "";
$scope.resultD = "";
$scope.executeRequest = function(parameterData) {
myHttpService.getServiceData(parameterData)
.then(function (response) {
assignToResultBasedOnType(response, parameterData.requestType);
});
}
$scope.executeMultipleRequestsWithStaticParameters = function(){
$scope.executeRequest({requestType: "A"});
$scope.executeRequest({requestType: "B"});
$scope.executeRequest({requestType: "C"});
$scope.executeRequest({requestType: "D"});
};
function assignToResultBasedOnType(response, type){
// Assign to response.data to
// $scope.resultA, $scope.resultB,
// $scope.resultC, or $scope.resultD,
// based upon value from type
// response.data and type should differ,
// based upon parameter "requestType" in each request
...........
};
// Assume other methods that may call upon $scope.executeMultipleRequestsWithStaticParameters or $scope.executeRequest
}
Now, I realize that "assignToResultBasedOnType" may not be the best way to handle the assignment to the correct property, but that is what we have today.
Usually, the four different result-properties receive the same type of object, but with different content, in the real life application.
Now, I want to simulate this behavior in my test.
MultipleRequestControllerTest
describe('MultipleRequestsController', function() {
var scope, controller, myHttpServiceMock, q, spy;
var lastRequestTypeParameter = [];
beforeEach(module('OppgaveregisteretWebApp'));
beforeEach(inject(function ($controller, $q, $rootScope, myHttpService) {
rootScope = $rootScope;
scope = rootScope.$new();
q = $q;
spy = spyOn(myHttpService, 'getServiceData');
controller = $controller('OpenDataController', {
$scope: scope,
httpService: httpService
});
}));
describe('executeMultipleRequestsWithStaticParameters ()', function () {
it('should update scope.result after running the service and receive response', function () {
// Prepare mocked promises.
myHttpServiceMock= q.defer();
spy.and.callFake(function (myParam) {
lastRequestTypeParameter.unshift(myParam.type);
return skjemaHttpServiceJsonMock.promise;
// Execute method
scope.executeMultipleRequestsWithStaticParameters();
// Resolve mocked promises
myHttpServiceMock.resolve(createFakeResponseBasedOnParameter(lastRequestTypeParameter.pop()));
scope.$digest();
// Check values
expect(scope.resultA).toBe("U");
expect(scope.resultB).toBe("X");
expect(scope.resultC).toBe("Y");
expect(scope.resultD).toBe("Z");
});
});
function createFakeResponseBasedOnParameter(requestType){
if (requestType==="A"){return {value:"U"}}
if (requestType==="B"){return {value:"X"}}
if (requestType==="C"){return {value:"Y"}}
if (requestType==="D"){return {value:"Z"}}
};
});
This is what happens in the test (discovered during debug):
The spy function runs four times, and pushes in the values to the array lastRequestTypeParameter, which will be [D, C, B, A], which values are supposed will be popped to read A-B-C-D, to reflect the real order of the requests.
However, here comes the problem: Resolve happens only once, and the same response is created for all four result-properties: {value:"U"}.
The correct list is selected internally, because the promise-chain uses the same parameter values as was used in the service-call (requestType), but they all receive data only on the first response. Thus, the result is:
$scope.resultA = "U"; $scope.resultB = "U", and so on.... instead of U, X, Y, Z.
So, the spy function runs four times, and I had assumed that four promises were returned, one for each call. But as of now, there is only one resolve() and one q.digest().
I have tried the following, to make things work:
Four q.defer()
Four resolves
Four digests
Return an array with four different objects, corresponding to what I would expect in working test. (Silly, I know, it differs from the expected object structure, but what don't you do when you try to tweak anything to get a surprisingly working result?).
None of these work. In fact, the first resolve causes the same result to all four properties, so adding more resolves and digests will make little difference.
I have tried to Google this issue, but all I find are either multiple promises for different services, multiple chain-functions (.then().then()...), or nested asynchronous calls (new promise object(s) inside chain).
What I need is a solution for independent promises, created by running the same function with different parameters.
So, I will end with the question I opened up with:
How do I resolve independent promises for the same function that has been run with different parameters in unit testing, and get different values?
Jasmine is Angular-friendly Jack of all trades. It is generally suitable for the majority of front-end testing cases. It lacks in spying/mocking functionality, while Sinon offers much more power.
This may be the reason why Mocha/Sinon/Chai modular bundle may be preferred at some point, but the good thing about its modularity is that Sinon isn't tied to the bundle. Besides its tight relations with Chai, it can also be used with Jasmine matchers.
The thing that makes Sinon a better choice than Jasmine spies is that it is capable of programming spies expectations (withArgs(...).called...) and stubs responses (withArgs(...).returns(...)). Blue-collar mocking becomes a piece of cake:
var sandbox;
var spy;
// beforeEach
sandbox = sinon.sandbox.create();
// similar to Jasmine spy without callThrough
spy = sandbox.stub(myHttpService, 'getServiceData');
...
// it
spy.withArgs('A').returns({value:"U"});
spy.withArgs('B').returns({value:"X"});
...
// afterEach
sandbox.restore(); // the thing that Jasmine does automatically for its spies
Regarding once-resolved promise, this is the expected behaviour. As a rule of thumb fresh promises should be returned from mocked functions, never an existing object with .returnValue in Jasmine (or .returns in Sinon).
A callback function should be used to return a fresh promise on each call. If the promise should be resolved with predefined value, there may be several patterns to achieve this, the most obvious is using a variable
var mockedPromiseValue;
...
spy = spyOn(myHttpService, 'getServiceData')
.and.callFake(() => $q.resolve(mockedPromiseValue));
...
mockedPromiseValue = ...;
myHttpService.getServiceData().then((result) => {
expect(result).toBe(...);
})
// rinse and repeat
$rootScope.$digest();

Meteor Mongo Not Getting Collection Data

I am trying to get a document from a collection, but it doesn't seem to be working.
when i use the find().fetch(), it returns only an empty array. my code is as follows.
var users = new Mongo.Collection("users");
console.log(users.find());
var userRecord = users.find().fetch();
var returnUserRecord = {};
if (userRecord.length >0){
returnUserRecord = {username:userRecord.username, loginHash:userRecord.loginHash};
console.log("if statement is not complete and the value of the return variable is");
console.log(returnUserRecord);
}
return returnUserRecord
I have checked the database directly and noticed that there is indeed a document in the collection with the command:
meteor mongo
if it makes any difference, all this code in the in the server js file, and is being called from from the client by: Meteor.Methods()/Meteor.call()
EDIT 1
i created another collections with new data from the client, and after selecting the correct database, and running the command:
meteor:PRIMARY> db.newCollection1.find()
i get:
{ "_id" : ObjectId("55d1fa4686ee75349cd73ffb"), "test1" : "asdasd", "test2" : "dsadsa", "test3" : "qweqwe" }
so this confirms that it is available in the database, but running the following in the client console, still doesnt return the result. (autopublish is installed. i tried removing autopublish and made the appropriate changes to subscribe to the table, but that didnt work either).
var coll = new Meteor.Collection('newCollection1');
coll.find().fetch()
this returned an empty array. i have also tried the same on the server.js code using:
meteor debug
but i am still getting an empty array. does anyone know what i might be doing wrong here?
SOLUTION
the solution for this was to create the collection variable in the Meteor object context. this way it can be accessed from the Meteor context.
i.e.
Meteor.coll = new Meteor.Collection('newCollection1');
Meteor.coll.find().fetch();
i hope this helps someone. depending on your code you may want to use a different context.
You don't wait for this subscription to complete, therefore you get empty array.
You should probably read this or this to better understand it.
The thing is you connect users variable to "users" collection, and when you call it, it isn't yet polluted with data (if you don't want to use subscription then maybe use helper - it's reactive so it will return proper value when subscrtiption is finished)
Did you subscribe your users collection somewhere?
if (Meteor.isServer) {
Meteor.publish("users", function(){
return Users.find({})
});
}
if (Meteor.isClient) {
Meteor.subscribe("users");
}
First of all some advice: you can not define a collection twice. If you call new Mongo.Collection("users") a second time you will get an error. Therefore, it should be a global variable an not inside a method.
What I can see in your code is that you are trying to use an array as if it were an object. userRecord.username wont work because userRecord has the value of the fetch() which returns an array.
You could either change your code to userRecord[0].username or loop over the results with forEach like so:
var users = new Mongo.Collection("users");
console.log(users.find());
users.find().forEach(function(singleUser){
console.log(EJSON.stringyfy(singleUser));
}
in order to return the first user, you would be better of using findOne which returns the first object in the result.

Angular Translate async timing issue with $translateProvider.useStaticFilesLoader

I am using the excellent Angular Translate ($translate) directive/service to deal with multiple Locale Languages and since I have multiple locale files I use the convenient $translateProvider.useStaticFilesLoader to load my translation files through a structure of localeAbbr.json, for example en.json, es.json, etc... I built a Plunker to show my open source project and that project uses the locale through Git raw files (pointing to the actual Github repository, meaning not local to the plunker demo). My project is built as a Directive and a Service, I made a small Plunker to show my timing issue with the JSON file loading.
All that to say that it seems $translateProvider.useStaticFilesLoader works asynchronous while I would really need it to be synchronous because by the time the plunker runs, the JSON files are not yet parsed while I already called a $translate.instant() on my messages.
I have a Plunker showing the problem.
And here is part of my quick Service demo:
app.factory('validationService', ['$filter', '$translate', function ($filter, $translate) {
var service = this;
var validationSummary = [];
var errorMessages = [
'INVALID_ALPHA',
'INVALID_ALPHA_SPACE',
'INVALID_ALPHA_NUM',
'INVALID_BOOLEAN'
];
//var $translate = $filter('translate');
for(var i=0, ln=errorMessages.length; i < ln; i++) {
validationSummary.push({
field: i,
message: $translate.instant(errorMessages[i])
});
}
// attach public functions
service.getValidationSummary = getValidationSummary;
return service;
// function declaration
function getValidationSummary() {
return validationSummary;
}
}]);
The $translateProvider configuration
app.config(['$translateProvider', function ($translateProvider) {
$translateProvider.useStaticFilesLoader({
prefix: 'https://rawgit.com/ghiscoding/angular-validation/master/locales/validation/',
suffix: '.json'
});
// load English ('en') table on startup
$translateProvider.preferredLanguage('en').fallbackLanguage('en');
}]);
Call my Service through the Controller:
app.controller("TestController", function($scope, validationService) {
var vm = this;
vm.displayValidationSummary = true;
vm.validationSummary = validationService.getValidationSummary();
});
and finally the HTML using the controller:
<div class="alert alert-danger alert-dismissable" ng-show="vm.displayValidationSummary">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true" ng-click="displayValidationSummary = false">×</button>
<h4><strong>{{ 'ERRORS' | translate }}!</strong></h4>
<ul>
<li ng-repeat="item in vm.validationSummary">{{item.field }}: {{item.message}}</li>
</ul>
</div>
Since I'm using AngularJS 1.3+, I also found that $translate only gets translated once, so the author suggest to use translateFilter.$stateful = true; and I tried but that doesn't seem to help.
Again here is the Plunker
I have been spending weeks on trying to find and code all kind of solution but I never got it to work and I'm really sad of seeing my raw translation code :(
Please Help!!!
EDIT
I realized that my question was not covering everything related to my problem. On top of the translation delay problem, I also have to pass extra arguments and that is a huge problem passing them to the translation anonymous function. By the time the promise is finished, the state of my arguments have already changed. For example:
$translate(validator.message).then(function(translation) {
// only log the invalid message in the $validationSummary
addToValidationSummary(formElmObj, translation);
// error Display
if(!isValid) {
updateErrorMsg(translation, isValid);
}else if(!!formElmObj && formElmObj.isValid) {
addToValidationSummary(formElmObj, '');
}
}, function(data) {
throw 'Failed to translate' + data;
});
When working with AngularJS, or JavaScript for that matter you really need to embrace the asynchronous paradigm. In order to make dealing with asynchronous code less cumbersome you can employ the use of Promises. Angular gives you a service called $q which does the heavy lifting for you
https://docs.angularjs.org/api/ng/service/$q
getting ones head around Promises can take time but well worth the effort in the long run.
Essentially what you need to do with your validationService is to make use of $translate's promise api which will give you the translation you require based on the supplied key when it is in a position to do so. What this boils down to is that you ask $translate for all of the translationId's you wish to get a translation for and when all have been fetched you populate the validationSummary array with your messages.
app.factory('validationService', ['$q', '$translate', function ($q, $translate) {
var translationsPromises = [],
validationSummary = [],
errorMessages = [
'INVALID_ALPHA',
'INVALID_ALPHA_SPACE',
'INVALID_ALPHA_NUM',
'INVALID_BOOLEAN'
];
angular.forEach(errorMessages, function(val, key) {
translationsPromises.push($translate(val));
});
$q.all(translationsPromises)
.then(function(translations) {
angular.forEach(translations, function(val, key) {
validationSummary.push({
filed: key,
message: val
});
});
})
.catch(function (err) {
console.error('Failed to translate error messages for validation summary', err);
});
// function declaration
function getValidationSummary() {
return validationSummary;
}
return {
getValidationSummary: getValidationSummary
};
}]);
I've forked your plunker and modified it to include the above sample
http://plnkr.co/edit/7DCwvY9jloXwfetKtcDA?p=preview
Another observation is that you are using the translate filter in the HTML. Please be aware that this can prove to be expensive if you have a large DOM as Angular will make the call to translate each key on every digest. An approach to consider would be to provide your vm with a labels object and use the $filter service to populate them upon controller instantiation.
I found out the answer to my problem of passing extra arguments to the anonymous function of the promise is to use Closures, in this way the variables are the same before the promise and inside it too. So I basically have to wrap my $translate call into the closure, something like the following:
(function(formElmObj, isValid, validator) {
$translate(validator.message).then(function(translation) {
message = message.trim();
// only log the invalid message in the $validationSummary
addToValidationSummary(formElmObj, message);
// error Display
if(!isValid) {
updateErrorMsg(message, isValid);
}else if(!!formElmObj && formElmObj.isValid) {
addToValidationSummary(formElmObj, '');
}
}, function(data) {
throw 'Failed to translate' + data;
});
})(formElmObj, isValid, validator);
and now finally, my variables are correct and keep the value at that point in time :)
While it is true that $translateProvider.useStaticFilesLoader does not return a promise, I looked inside the $translate service and found that it provides a handy callback onReady() which does return a promise. This callback is invoked when the $translate service has finished loading the currently selected language, and is useful for making sure that instant translations will work as expected after page initialization:
$translate.onReady(function () {
// perform your instant translations here
var translatedMsg = $translate.instant('INVALID_ALPHA');
});

Deps autorun in Meteor JS

Decided to test out Meteor JS today to see if I would be interested in building my next project with it and decided to start out with the Deps library.
To get something up extremely quick to test this feature out, I am using the 500px API to simulate changes. After reading through the docs quickly, I thought I would have a working example of it on my local box.
The function seems to only autorun once which is not how it is suppose to be working based on my initial understanding of this feature in Meteor.
Any advice would be greatly appreciated. Thanks in advance.
if (Meteor.isClient) {
var Api500px = {
dep: new Deps.Dependency,
get: function () {
this.dep.depend();
return Session.get('photos');
},
set: function (res) {
Session.set('photos', res.data.photos);
this.dep.changed();
}
};
Deps.autorun(function () {
Api500px.get();
Meteor.call('fetchPhotos', function (err, res) {
if (!err) Api500px.set(res);
else console.log(err);
});
});
Template.photos.photos = function () {
return Api500px.get();
};
}
if (Meteor.isServer) {
Meteor.methods({
fetchPhotos: function () {
var url = 'https://api.500px.com/v1/photos';
return HTTP.call('GET', url, {
params: {
consumer_key: 'my_consumer_key_here',
feature: 'fresh_today',
image_size: 2,
rpp: 24
}
});
}
});
}
Welcome to Meteor! A couple of things to point out before the actual answer...
Session variables have reactivity built in, so you don't need to use the Deps package to add Deps.Dependency properties when you're using them. This isn't to suggest you shouldn't roll your own reactive objects like this, but if you do so then its get and set functions should return and update a normal javascript property of the object (like value, for example), rather than a Session variable, with the reactivity being provided by the depend and changed methods of the dep property. The alternative would be to just use the Session variables directly and not bother with the Api500px object at all.
It's not clear to me what you're trying to achieve reactively here - apologies if it should be. Are you intending to repeatedly run fetchPhotos in an infinite loop, such that every time a result is returned the function gets called again? If so, it's really not the best way to do things - it would be much better to subscribe to a server publication (using Meteor.subscribe and Meteor.publish), get this publication function to run the API call with whatever the required regularity, and then publish the results to the client. That would dramatically reduce client-server communication with the same net result.
Having said all that, why would it only be running once? The two possible explanations that spring to mind would be that an error is being returned (and thus Api500px.set is never called), or the fact that a Session.set call doesn't actually fire a dependency changed event if the new value is the same as the existing value. However, in the latter case I would still expect your function to run repeatedly as you have your own depend and changed structure surrounding the Session variable, which does not implement that self-limiting logic, so having Api500px.get in the autorun should mean that it reruns when Api500px.set returns even if the Session.set inside it isn't actually doing anything. If it's not the former diagnosis then I'd just log everything in sight and the answer should present itself.

How does AngularJS return a value from async call?

Watch this video,
https://www.youtube.com/watch?v=IRelx4-ISbs
You'll find that the code has a line wrote this:
$scope.twitterResult = $scope.twitter.get({q:$scope.searchTerm});
This is a litter quirk:
the 'get' method of 'twitter' is obviously a async function, how does it return a value to $scope.twitterResult???
jsFiddle(Can't work cause the twitter API has changed):
http://jsfiddle.net/johnlindquist/qmNvq/
This code $scope.twitter.get({q:$scope.searchTerm}); return defer object. Angular view arranged so that view will be update when defer object resolve. It's just a convenience.
$scope.twitterResult = $scope.twitter.get({q:$scope.searchTerm});
Your code is good for only angular binding.
But if you need to get data on run time, you need to write this below format.
If $scope.twitter is a URL,Then write it
$http.get($scope.twitter, {q:$scope.searchTerm}).success(function (response) {
$scope.twitterResult=response;
}
$http is must defined in contoller

Categories

Resources