AngularJS Resolving a Promise - javascript

I am learning how to use resolve from an example, and applying it on to my Todo script.
Then I realised an issue, that the example is only showing me how to resolve GET call to get me the Todo List when I first visit this route.
However, in the same route same page I have an Add button to POST new todo item, also a Clear button to DELETE completed items.
Looking at my $scope.addTodo = function() { and $scope.clearCompleted = function () { I want to Resolve my TodoList again after the action. How can I do that?
Here is my code. In my code, the initial resolve: { todos: TodosListResl } is working, it hits TodosListResl function and produces the promise. However, I don't know what to do with addTodo and clearComplete when I want to resolve the todo list again.
main.js
var todoApp = angular.module('TodoApp', ['ngResource', 'ui']);
todoApp.value('restTodo', 'api/1/todo/:id');
todoApp.config(function ($locationProvider, $routeProvider) {
$routeProvider.when("/", { templateUrl: "Templates/_TodosList.html",
controller: TodosListCtrl, resolve: { todos: TodosListResl } });
$routeProvider.otherwise({ redirectTo: '/' });
});
//copied from example, works great
function TodoCtrl($scope, $rootScope, $location) {
$scope.alertMessage = "Welcome";
$scope.alertClass = "alert-info hide";
$rootScope.$on("$routeChangeStart", function (event, next, current) {
$scope.alertMessage = "Loading...";
$scope.alertClass = "progress-striped active progress-warning alert-info";
});
$rootScope.$on("$routeChangeSuccess", function (event, current, previous) {
$scope.alertMessage = "OK";
$scope.alertClass = "progress-success alert-success hide";
$scope.newLocation = $location.path();
});
$rootScope.$on("$routeChangeError",
function (event, current, previous, rejection) {
alert("ROUTE CHANGE ERROR: " + rejection);
$scope.alertMessage = "Failed";
$scope.alertClass = "progress-danger alert-error";
});
}
//also copied from example, works great.
function TodosListResl($q, $route, $timeout, $resource, restTodo) {
var deferred = $q.defer();
var successCb = function(resp) {
if(resp.responseStatus.errorCode) {
deferred.reject(resp.responseStatus.message);
} else {
deferred.resolve(resp);
}
};
$resource(restTodo).get({}, successCb);
return deferred.promise;
}
//now, problem is here in addTodo and clearCompleted functions,
//how do I call resolve to refresh my Todo List again?
function TodosListCtrl($scope, $resource, restTodo, todos) {
$scope.src = $resource(restTodo);
$scope.todos = todos;
$scope.totalTodos = ($scope.todos.result) ? $scope.todos.result.length : 0;
$scope.addTodo = function() {
$scope.src.save({ order: $scope.neworder,
content: $scope.newcontent,
done: false });
//successful callback, but how do I 'resolve' it?
};
$scope.clearCompleted = function () {
var arr = [];
_.each($scope.todos.result, function(todo) {
if(todo.done) arr.push(todo.id);
});
if (arr.length > 0) $scope.src.delete({ ids: arr });
//successful callback, but how do I 'resolve' it?
};
}

I think you're missing the point of resolve. The point of resolve is to " delay route change until data is loaded. In your case, you are already on a route, and you want to stay on that route. But, you want to update the todos variable on the successful callback. In this case, you don't want to use resolve. Instead, just do what needs to be done. For example
$scope.addTodo = function() {
$scope.src.save({ order: $scope.neworder,
content: $scope.newcontent,
done: false }, function () {
todos.push({ order: $scope.neworder,
content: $scope.newcontent,
done: false });
});
//successful callback, but how do I 'resolve' it?
};
As a side point, I noticed you're using _ most likely from the Underscore library. You don't need to use another library for that because Angular already has $angular.forEach().

Related

cant update jasmine spy

Hi I have a Angular service that uses another service that loads data from the local storage on init.
angular
.module('app')
.factory('localStorage', function ($window)
{
if (!$window.localStorage)
{
// throw Error
}
return $window.localStorage;
});
angular
.module('app')
.factory('session', function (localStorage)
{
var container = JSON.parse(localStorage.getItem('sessionContainer'));
return {
getUser: getUser
};
});
Now i want to test the session service.
describe('SessionService', function ()
{
var service;
var localStorageMock;
// Load the module.
beforeEach(module('appRegistration'));
// Create mocks.
beforeEach(function ()
{
logMock = {};
localStorageMock = jasmine.createSpyObj('localStorageServiceMockSpy', ['setItem', 'getItem']);
localStorageMock.getItem.and.returnValue('{}');
module(function ($provide)
{
$provide.value('localStorage', localStorageMock);
});
inject(function (_session_)
{
service = _session_;
});
});
it('should call `getItem` on the `localStorageService` service', function ()
{
expect(localStorageMock.getItem).toHaveBeenCalledWith('sessionContainer');
});
describe('getUser method', function ()
{
it('should return an empty object when the user is not set', function ()
{
var result = service.getUser();
expect(result).toEqual({});
});
it('should return the user data', function ()
{
// localStorageMock.getItem.and.returnValue('{"user":{"some":"data"}}');
var result = service.getUser();
expect(result).toEqual({some: 'user data'});
});
});
});
As you can see in the should return the user data section.
I need a way to update the container so getUser returns the expected data.
I tried to update the getItem spy, but this does not work. The localStorageMock is already injected in the session service when i want to change the spy.
Any help?
The most simple way is to have a variable with mocked value that is common for both function scopes:
var getItemValue;
beforeEach({
localStorage: {
getItem: jasmine.createSpy().and.callFake(function () {
return getItemValue;
}),
setItem: jasmine.createSpy()
}
});
...
it('should return the user data', function ()
{
getItemValue = '{"user":{"some":"data"}}';
inject(function (_session_) {
service = _session_;
});
var result = service.getUser();
expect(result).toEqual({some: 'user data'});
});
Notice that inject should be moved from beforeEach to it for all specs (the specs that don't involve getItemValue may use shorter syntax, it('...', inject(function (session) { ... }))).
This reveals the flaw in service design that makes it test-unfriendly.
The solution is to make container lazily evaluated, so there is time to mock it after the app was bootstrapped with inject:
.factory('session', function (localStorage)
{
var containerCache;
function getUser() {
...
return this.container;
}
return {
get container() {
return (containerCache === undefined)
? (containerCache = JSON.parse(localStorage.getItem('sessionContainer')))
: containerCache;
},
getUser: getUser
};
});
Additionally, this makes possible to test session.container as well. In this case localStorageMock.getItem spy value may be redefined whenever needed.

Undefined scope variable in AngularJS app

I am trying to set a Boolean property on an element in my array object, which I have in my scope.
In the code given below, when I try to set tasks[id].deleted = true, I get the following error.
angular.js:12798 TypeError: Cannot set property 'deleted' of undefined
at Scope.$scope.delete (main.js:54)
Where am I going wrong?
My whole code file is:
angular.module('ngMaterialTaskListApp')
.controller('MainCtrl', function ($scope, $mdDialog, TaskService) {
// Model from which View populates data
$scope.tasks = [];
console.log($scope.tasks);
$scope.showAddDialog = function (ev) {
$mdDialog.show({
controller: DialogController,
templateUrl: '../views/add-dialog-template.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose: true,
fullscreen: true, //Only for xs and sm screen sizes
locals: { //For DialogController, as tasks
tasks: $scope.tasks
}
});
};
/*----------- Function to delete items onClick of delete icon -----------*/
$scope.delete = function (id) {
console.log($scope.tasks[id]);
console.log(id);
// console.log($scope.tasks[id].name);
$scope.tasks[id].deleted = true;
};
/*----------- DialogController function -----------*/
function DialogController($scope, $mdDialog, tasks) {
$scope.task = {};
$scope.hide = function () {
$mdDialog.hide();
//TODO Add a message as to what happened
};
$scope.cancel = function () {
$mdDialog.cancel();
//TODO Add a message as to what happened
};
/*----------- Method show the add dialog -----------*/
$scope.addData = function () {
if (null !== $scope.task.name && null !== $scope.task.description) {
/*----------- Using moment.js to parse date and time -----------*/
$scope.task.date = moment($scope.task.date, '').format('DD MMM YYYY');
$scope.task.time = moment($scope.task.time, '').format('h:mm a');
$scope.task.done = false; // Every new task is pending!
$scope.task.deleted = false; // Every new task exists!
var GlobalID = Date.now();
console.log(GlobalID);
$scope.task.id = GlobalID;
/*----------- Performing http POST -----------*/
TaskService.postTask($scope.task);
/*----------- Pushing to tasks object in $scope of MainCtrl -----------*/
// Have to update tasks again
tasks.push($scope.task);
$scope.hide();
console.log(tasks); //DEBUGGING
} else {
//TODO ADD INVALID/NULL DATA WARNING
}
};
};
// DEPRECATED - USED FOR DATA WHEN SERVER NOT AVAILABLE
TaskService.getTasks().then(function (response) {
$scope.tasks = response.data.tasks;
}, function (error) {
console.log(error + "This");
});
//USING THIS TO GET DATA FROM SERVER
TaskService.getAllTasks().then(function (response) {
// console.log(response.data);
$scope.tasks = response.data;
console.log($scope.tasks);
});
});
How is your html? I bet is like this inside a button in ng-repeat:
ng-click="delete(task.id)"
Try putting like this:
ng-click="delete($index)"

how to retrieve data by id with angularfire

i used a tutorial to create a angularfire chat app. it is a standalone app that uses ui-router. I integrated it succssfully as a view in my app but that is not practical. I need to be able to use the chat on any view I am at. I am stuck at moving a resolve function to a controller. I have read some docs and I believe it is returning a promise that I need to resolve in the controller. the link to the tutorial is here.
tutorial
here is the ui-router I am trying to get away from
.state('channels.direct', {
url: '/{uid}/messages/direct',
templateUrl: 'views/chat/_message.html',
controller: 'MessageController',
controllerAs: 'messageCtrl',
resolve: {
messages: function ($stateParams, MessageService, profile) {
return MessageService.forUsers($stateParams.uid, profile.$id).$loaded();
},
channelName: function ($stateParams, UserService) {
return UserService.all.$loaded().then(function () {
return '#' + UserService.getDisplayName($stateParams.uid);
});
}
}
})
The message service
var channelMessagesRef = new Firebase(AppConstant.FirebaseUrl + 'channelMessages');
var userMessagesRef = new Firebase(AppConstant.FirebaseUrl + 'userMessages')
return {
forChannel: function (channelId) {
return $firebaseArray(channelMessagesRef.child(channelId));
},
forUsers: function (uid1, uid2) {
var path = uid1 < uid2 ? uid1 + '/' + uid2 : uid2 + '/' + uid1;
return $firebaseArray(userMessagesRef.child(path));
}
};
the user service
var usersRef = new Firebase(AppConstant.FirebaseUrl + 'users');
var connectedRef = new Firebase(AppConstant.FirebaseUrl + '.info/connected');
var users = $firebaseArray(usersRef);
return {
setOnline: function (uid) {
var connected = $firebaseObject(connectedRef);
var online = $firebaseArray(usersRef.child(uid + '/online'));
connected.$watch(function () {
if (connected.$value === true) {
online.$add(true).then(function (connectedRef) {
connectedRef.onDisconnect().remove();
});
}
});
},
getGravatar: function (uid) {
return '//www.gravatar.com/avatar/' + users.$getRecord(uid).emailHash;
},
getProfile: function (uid) {
return $firebaseObject(usersRef.child(uid));
},
getDisplayName: function (uid) {
return users.$getRecord(uid).displayName;
},
all: users
};
here is what I have so far in the controller
$scope.directMessage = function (uid) {
UserService.all.$loaded().then(function () {
$scope.selectedChatUser = '#' + UserService.getDisplayName(uid);
});
$scope.selectedChatUserMessages = MessageService.forUsers(uid, profile.$id).$loaded();
};
I am returning the
$scope.selectedChatUser
fine. the issue is with the Message Service
this is the what i am currently returning from the message service
$$state: Object
__proto__: Promise
how do i resolve this?
You're trying to return from inside a promise in your channelName function.
The object you're getting back is an unresolved promise. You want the resolved data from the promise injected into your controller.
You need to create a to return from this function.
.state('channels.direct', {
url: '/{uid}/messages/direct',
templateUrl: 'views/chat/_message.html',
controller: 'MessageController',
controllerAs: 'messageCtrl',
resolve: {
messages: function ($stateParams, MessageService, profile) {
return MessageService.forUsers($stateParams.uid, profile.$id).$loaded();
},
channelName: function ($stateParams, UserService, $q) {
// create a deferred for this function
var deferred = $q.defer();
// load async data with UserService.all's promise
UserService.all.$loaded()
.then(function () {
var name = UserService.getDisplayName($stateParams.uid);
deferred.resolve(name);
});
// return promise
return deferred.promise;
}
}
})
However in getDisplayName I would just recommend returning back the object rather than just the name, as the entire set is synchronized by Firebase.

Jasmine test using spyon with $httpBackend not working

I am trying to write a jasmine test on some javascript using spyon over a method that uses $http. I have mocked this out using $httpBackend and unfortunately the spy doesn't seem to be picking up the fact the method has indeed been called post $http useage. I can see it being called in debug, so unsure why it reports it hasn't been called. I suspect I have a problem with my scope usage ? or order of $httpBackend.flush\verify ?:
Code under test
function FileUploadController($scope, $http, SharedData, uploadViewModel) {
Removed variables for brevity
.....
$scope.pageLoad = function () {
$scope.getPeriods();
if ($scope.uploadViewModel != null && $scope.uploadViewModel.UploadId > 0) {
$scope.rulesApplied = true;
$scope.UploadId = $scope.uploadViewModel.UploadId;
$scope.linkUploadedData();
} else {
$scope.initDataLinkages();
}
}
$scope.initDataLinkages = function () {
$http({ method: "GET", url: "/api/uploadhistory" }).
success(function (data, status) {
$scope.status = status;
$scope.setUploadHistory(data);
}).
error(function (data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
}
$scope.setUploadHistory = function (data) {
if ($scope.UploadId > 0) {
$scope.currentUpload = data.filter(function (item) {
return item.UploadId === $scope.UploadId;
})[0];
//Remove the current upload, to prevent scaling the same data!
var filteredData = data.filter(function (item) {
return item.UploadId !== $scope.UploadId;
});
var defaultOption = {
UploadId: -1,
Filename: 'this file',
TableName: null,
DateUploaded: null
};
$scope.UploadHistory = filteredData;
$scope.UploadHistory.splice(0, 0, defaultOption);
$scope.UploadHistoryId = -1;
$scope.UploadTotal = $scope.currentUpload.TotalAmount;
} else {
$scope.UploadHistory = data;
}
}
Test setup
beforeEach(module('TDAnalytics'));
beforeEach(inject(function (_$rootScope_, $controller, _$httpBackend_) {
$rootScope = _$rootScope_;
$scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
var sharedData = { currentBucket: { ID: 1 } };
controller = $controller('FileUploadController', { $scope: $scope, SharedData: sharedData, uploadViewModel: null });
$httpBackend.when('GET', '/api/Periods').respond(periods);
$httpBackend.when('GET', '/api/uploadhistory').respond(uploadHistory);
$scope.mappingData = {
FieldMappings: [testDescriptionRawDataField, testSupplierRawDataField],
UserFields: [testDescriptionUserField, testSupplierUserField]
};
}));
afterEach(function() {
testDescriptionRawDataField.UserFields = [];
testSupplierRawDataField.UserFields = [];
testTotalRawDataField.UserFields = [];
$httpBackend.flush();
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
Working test:
it('pageLoad should call linkUploadedData when user has navigated to the page via the Data Upload History and uploadViewModel.UploadId is set', function () {
// Arrange
spyOn($scope, 'linkUploadedData');
$scope.uploadViewModel = {UploadId: 1};
// Act
$scope.pageLoad();
// Assert
expect($scope.rulesApplied).toEqual(true);
expect($scope.linkUploadedData.calls.count()).toEqual(1);
});
Test that doesn't work (but should. returns count-0 but is called)
it('pageLoad should call setUploadHistory when data returned successfully', function () {
// Arrange
spyOn($scope, 'setUploadHistory');
// Act
$scope.initDataLinkages();
// Assert
expect($scope.setUploadHistory.calls.count()).toEqual(1);
});
The issue is you call httpBackend.flush() after the expect, which means success is called after you do your tests. You must flush before the expect statement.
it('pageLoad should call setUploadHistory when data returned successfully',
inject(function ($httpBackend, $rootScope) {
// Arrange
spyOn($scope, 'setUploadHistory');
// Act
$scope.initDataLinkages();
$httpBackend.flush();
$rootScope.$digest()
// Assert
expect($scope.setUploadHistory.calls.count()).toEqual(1);
}));
You may need to remove the flush statement from after your tests, but it probably should not be there anyway because usually it's a core part of testing behaviour and should be before expect statements.

Watching changed in the service from the controller

I am trying to listen to changes in my injected service (self-updating) in the controller. In the below example you'll find two $watch cases - one that works but I don't know exactly why and one that was obvious to me, yet doesn't work. Is the second example the right way to do it? Isn't that code duplication? What is the right way to do it?
Service:
app.factory("StatsService", [
'$timeout', 'MockDataService',
function ($timeout, MockDataService) {
var service, timeout;
timeout = 5000;
service = {
fetch: function () {
// Getting sample data, irrelevant, however this is what updates the data
return this.data = MockDataService.shuffle();
},
grab: function () {
this.fetch();
return this.update();
},
update: function () {
var _this = this;
return $timeout(function () {
return _this.grab();
}, timeout);
}
};
service.grab();
return service;
}
]);
Controller:
app.controller("StatsController", [
'$scope', 'StatsService',
function ($scope, StatsService) {
var chart;
$scope.stats = StatsService;
$scope.test = function (newValue) {
if (arguments.length === 0) {
return StatsService.data;
}
return StatsService.data = newValue;
};
// This doesn't work
$scope.$watch('stats', function (stats) {
return console.log('meh');
});
// This works, don't know why
$scope.$watch('test()', function (stats) {
return console.log('changed');
});
}
]);
See the third parameter for $watch: objectEquality
Compare object for equality rather than for reference.
However if you're only interested in watching the returned data, then you should do:
$scope.$watch('stats.data', function (stats) {
return console.log('meh');
});
You could use $rootScope events. For example inside the service you could dispatch an event with $rootScope.$broadcast("somethingFetched", data) and catch it in the controller $scope.$on("somethingFetched", function(event, data) { $scope.data = data }).
More details you could find in the documentation http://docs.angularjs.org/api/ng.$rootScope.Scope

Categories