AngularJS $http Interceptors (Explanation and Examples)

bcswartz 6,751 views 14 slides Feb 19, 2015
Slide 1
Slide 1 of 14
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
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.


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.

Questions?