Created
October 17, 2015 11:22
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* 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', ... ); | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** | |
* | |
* 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