In this lesson Brett will show you how to use $provide.decorator
to cleanly add functionality to AngularJS services and keep your concerns wonderfully separated.
Brett Shollenberger: Today, we'll use the decorator pattern to extend the functionality of our Angular services. We'll be creating a system model to display error messages to our user on the view. The model itself will get an error number from the API.
It's a fairly common occurrence that we'll need to parse one format into another format that's ready for presentation. Since this is a presentation concern and not a model concern, we'll want to encapsulate this parsing logic in another portion of our application.
Angular gives us a great method to do this, namely provide.decorator. This will allow us to create a presenter, which is a special type of decorator that creates a bridge between the model layer and the view layer.
Here, we use provide.decorator to decorate our system object and add new methods and properties on the delegated object. This works quite a bit differently from the way the presenter pattern or the decorator pattern works in other languages.
Because we can't sometimes choose the decorator objects and other times not to, Angular's dependency injection system returns singleton objects, meaning there's only one instance of every service.
Still, it makes sense for us to encapsulate our view-specific logic elsewhere so it's easier for us to refactor and understand the different components of our system.
Another reason we may wish to use a decorator in Angular is to extend other external services without diving into their source code or modifying them directly.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!