Using URL Interpolation With $http In AngularJS
When I say "interpolation" in this context, what I mean is that AngularJS would move items from the request data into the URL where the data could be substituted-in for variable labels. So, for example, if I gave $resource the URL:
... and I made a request that contained the key, "id", with the value, "4", the value of said ID would be merged into the URL:
Notice that the URL component, ":id", was replaced with the outgoing request value, "4". It would be easy enough to build these URLs with string concatenation; but, the interpolation approach makes the code easier to read - less noise, more signal.
In order to get this functionality to work with the underlying $http service, I would have to create some sort of proxy to the $http service that would manage the interpolation for me. As an experiment, I tried creating a new service, "httpi". The httpi service applies the URL interpolation to the request configuration object before passing the request config off to the underlying $http service.
To see this in action, I'm going to make several requests to the following URL with different sets of outgoing request data:
api/friends/( :listCommand | :id/:itemCommand )
Notice that this URL has three labels that can be interpolated:
My httpi service will strip out the (.|.) notation - it's just there to make the "happy paths" a bit more obvious.
As you can see, the httpi service does nothing more than call interpolateUrl() before passing the config data off to the underlying $http service.
When we run the above code, we get the following requests in the network activity:
As you can see, the outgoing request data was interpolated in the URL. And, while you can't see it in this output, the corresponding request data was stripped out of the "params" and "data" collections (if they existed) in order to prevent redundant data points.
The URL interpolation was one of the features of $resource that I really liked. I'm happy to see that it's not too hard to implement the same feature on top of the $http service in AngularJS. This is definitely a direction that I want to move in.
Want to use code from this post? Check out the license.
I took this concept, rolled it up into its own AngularJS module, and then grew the features ever so slightly:
What's the max length of name that we can post to server?
Thanks! I found this blog post useful, especially the interpolateUrl part
Great post, this was very helpful. Thanks! :)
(.|.) <-- definitely a happy path