Last active
August 29, 2015 14:18
-
-
Save cadrogui/286669e5fb17faeae0fb to your computer and use it in GitHub Desktop.
Interpolate Urls in angular, i used this code for maintain the same logic in router backend (SailsJS) and front-end requests (AngularJS), interpolated urls are like '/reportes/:categoria_id', and the helper method replace the label with a value for generate a clean, understandable and maintainable request logics
This file contains hidden or 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
| // I use this method as a service like this: | |
| App.service("Helpers", [ | |
| function() { | |
| var method = {}; | |
| method.interpolateUrl = function(url, obj, fn){ | |
| var interpolated = [] | |
| var paramLen = Object.keys(obj[0]).length | |
| url.forEach(function(e, i){ | |
| var ur = e.url | |
| var matches = ur.match(/:([a-z]\w*)/gi).length | |
| var aux | |
| if(matches == paramLen){ | |
| method._matches = function(rs){ | |
| rs.replace(/:([a-z]\w*)/gi, function($0, label){ | |
| if(obj[i].hasOwnProperty(label)){ | |
| aux = rs.replace($0, obj[i][label]) | |
| method._matches(aux) | |
| } | |
| }); | |
| interpolated.push(aux); | |
| } | |
| method._matches(ur); | |
| }else{ | |
| console.log("Interpolate Mismatch", url, obj); | |
| } | |
| }); | |
| var interpolatedU = interpolated.filter(function(e,p){ | |
| return interpolated.indexOf(e) == p | |
| }); | |
| return fn(interpolatedU) | |
| } | |
| return method; | |
| } ]) | |
| // can be used in a factory with promises | |
| App.factory("AppFactory", [ "$http", "$rootScope", "$q", "Helpers", | |
| function($http, $rootScope, $q, Helpers) { | |
| var method = {}; | |
| method.exampleMethod = function(obj){ | |
| var deferred = $q.defer(); | |
| var urls = [ | |
| { url: API_URL + "/reportes/:categoria_id/reservas/:reserva_id/empresas/:empresa_id" } | |
| ]; | |
| var promises = []; | |
| Helpers.interpolateUrl(urls, obj, function(interpolatedUrls){ | |
| urls.forEach(function(url, i){ | |
| promises.push($http({ method: "GET", url: interpolatedUrls[i] })) | |
| }); | |
| $q.all(promises).then(function(data){ | |
| deferred.resolve({ | |
| "promisedRequest": data | |
| }) | |
| }) | |
| }) | |
| return deferred.promise; | |
| }; | |
| return method; | |
| } ]) | |
| // in the controller the usage is very easy: | |
| var obj = [{ categoria_id: 12, reserva_id: 66, evaluacion_id: 88, empresa_id:829 }] | |
| AppFactory.exampleMethod(obj).then(function(promise){ | |
| console.log(promise) | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment