AngularJS $http Interceptors (Explanation and Examples)
bcswartz
6,751 views
14 slides
Feb 19, 2015
Slide 1 of 14
1
2
3
4
5
6
7
8
9
10
11
12
13
14
About This Presentation
Slide deck from a 10-minute lightning talk on AngularJS $http interceptors (what they are, how to write them, and what you can use them for) presented at the AngularJS Meetup hosted by Difference Engine in Washington DC on Feb. 18, 2015.
Size: 285.89 KB
Language: en
Added: Feb 19, 2015
Slides: 14 pages
Slide Content
AngularJS $http Interceptors Explanation and Examples Brian Swartzfager [email protected] http://thoughtdelimited.org
What are $http Interceptors They are event functions triggered during the lifecycle of an HTTP call made via AngularJS . They will run anytime you execute: $http $resource $ httpBackend
Types of Interceptors request ( configuration ) Receives and returns a configuration object that defines the outgoing HTTP call requestError ( rejection ) Receives a rejection object when a previous interceptor (like a request interceptor) returns an error or rejection response ( response ) Receives and returns a response object from a successful HTTP call responseError ( rejection ) Receives a rejection object when a previous response interceptor returns an error or rejection Documentation: https://docs.angularjs.org/api/ng/service/$http#interceptors
C reated as Service F actory F unctions
Added to the $ httpProvider Interceptors A rray
Uses For Interceptors Useful anytime you need to apply the same checks/actions on HTTP requests and responses throughout your application (“cross-cutting concerns”) Configuring the outgoing requests in a certain way Altering the incoming response for easier consumption Handling certain response errors Checking authentication status
Conditional Interceptor Behavior Use the properties and functions of an injected object to control or suppress interceptor behavior. An object in the $ rootScope Or an Angular service
r equest Example
responseError Example
responseError : 400 error
responseError : 403 error
responseError : 500 server error
response Example Better approach: M ove the location management logic to a service function and inject that service into this interceptor and the responseError interceptor.