Skip to content

Instantly share code, notes, and snippets.

@GuyMograbi
Created October 17, 2015 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GuyMograbi/23b72cd1cc8928106939 to your computer and use it in GitHub Desktop.
Save GuyMograbi/23b72cd1cc8928106939 to your computer and use it in GitHub Desktop.
Find or create pattern in angular - saw someone implemented it in a wrong way and thought to blog about it
/**
*
* The WRONG way
*
* - requires method to be in Controller - see $scope and $http usage.. lack of separation.
* - copy paste of callback.. lack of use of promise behavior, no proper error handling
*
**/
function getOrCreate() {
$http({
'method' : 'GET',
'url' : '/backend/items',
}
}).then(function(result) {
$scope.item = result.data;
if (!$scope.item) {
create().then(function(result) {
$scope.item = result.data;
$scope.$watch('item', ... );
});
}else{
$scope.$watch('item', ... );
}
});
}
/***
*
* The Better Way
*
* - http calls made by service - unit test friendly, separation of concerns, reuse ability increases.
* - usage of promise behavior, single promise handles, single callback required
* - this also allows to have entire getOrCreate function in service and expose a new api if required.. (i did not want that)
* - less lines, more maintainable and more readable
*
**/
function getOrCreate() {
MyService.get().then(function getCallback(result) {
return !result.data) ? MyService.create() : result;
}
}).then( function success(result){
$scope.item = result.data;
}, function error(){
toastr.error('failed getting item','failed');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment