Historical Post: This article was originally written in 2015. The technology discussed may be outdated or deprecated. Keeping it here for historical reference and to show I’ve been blogging since 2015!
Overview
This article addresses a common question about implementing promises and HTTP factories correctly in AngularJS applications. The approach shared demonstrates streamlined usage patterns adapted through experience.
Key Concept: Promise Chaining
The $http service supports promise chaining, enabling developers to write cleaner factory code. This approach separates concerns effectively.
Factory Implementation
The example factory includes:
- A
getData()function that makes HTTP GET requests - A
getDataComplete()handler for successful responses - A
getDataFailed()handler for error management - Dependency injection using the array notation pattern
The factory returns response data directly, simplifying downstream consumption.
Controller Usage
The accompanying controller demonstrates how to consume the factory’s promise-based API. The controller:
- Injects the factory as a dependency
- Calls the factory method and chains
.then()for data handling - Binds returned data to the view model for template binding
Benefits
This approach provides dead simple controller code by encapsulating HTTP logic in the factory layer, improving testability and reusability across the application.