I'm moving my subject data to a service and trying to smart about the code but I'm running into some issues.
When I turn off my API server and run the create function, I expect just the onRejected
callback to be fired. Rather both the onFulfilled
and the onRejected
callbacks are being fired.
Service
(function(){
'use strict';
angular
.module('app')
.factory('$cmSubjectData', $cmSubjectData);
function $cmSubjectData($log, Restangular, $mdToast) {
var service = {
getAll: getAll,
getById: getById,
update: update,
create: create,
destroy: destroy
};
return service;
function getAll() {
return subjects().getList().then(handleSuccess, handleError('Error getting all subjects'));
}
function getById(id) {
return subjects().one(id).get().then(handleSuccess, handleError('Error getting this subject'));
}
function update(subject) {
Restangular.all('subjects')
.post(subject)
.then(handleSuccess, handleError('Error updating subject'));
}
function create(subject) {
Restangular.all('subjects')
.post(subject)
.then(successToast(subject.basicInfo.firstName + ' has been created'), handleError('Error creating subject'));
}
function destroy(id) {
var subject = subjects().one(id);
subject.remove()
.then(successToast('Subject has been deleted!'), handleError('There was an error deleting this subject'));
}
// Private Functions
function subjects() {
return Restangular.service('subjects');
}
function handleSuccess(data) {
$log.info('Success');
return data;
}
function handleError(error) {
return function () {
$log.warn(error);
};
}
function successToast(content) {
$mdToast.show(
$mdToast.simple()
.content(content)
);
}
}
})();
Controller
(function() {
'use strict';
angular
.module('app')
.controller('SubjectNewCtrl', SubjectNewCtrl);
function SubjectNewCtrl($cmSubjectData) {
var vm = this;
vm.subject = {};
vm.createSubject = $cmSubjectData.create;
}
})();
View where function is called:
<button ng-click="vm.createSubject(vm.subject)">Add</button>
Any help would be appreciated.