SlideShare a Scribd company logo
1 of 28
Download to read offline
Rodrigo Branas – @rodrigobranas - http://www.agilecode.com.br
Interceptors com AngularJS
Um interceptor é um tipo de serviço que
permite a interceptação das requisições e
respostas do serviço $http.
1. app.factory("nomeDoInterceptorA",	
  function	
  ($q)	
  {	
  
2. 	
  	
  return	
  {	
  
3. 	
  	
  	
  	
  request:	
  function	
  (config)	
  {	
  
4. 	
  	
  	
  	
  	
  	
  return	
  config;	
  
5. 	
  	
  	
  	
  },	
  
6. 	
  	
  	
  	
  requestError:	
  function	
  (rejection)	
  {	
  
7. 	
  	
  	
  	
  	
  	
  return	
  $q.reject(rejection);	
  
8. 	
  	
  	
  	
  },	
  
9. 	
  	
  	
  	
  response:	
  function	
  (response)	
  {	
  
10. 	
  	
  	
  	
  	
  	
  return	
  response;	
  
11. 	
  	
  	
  	
  },	
  
12. 	
  	
  	
  	
  responseError:	
  function	
  (rejection)	
  {	
  
13. 	
  	
  	
  	
  	
  	
  return	
  $q.reject(rejection);	
  
14. 	
  	
  	
  	
  }	
  
15. 	
  	
  };	
  
16. });
Configurando o interceptor
O serviço $http possui um array de
interceptors que podem ser configurados na
inicialização da aplicação.	
  
1. app.config(function	
  ()	
  {	
  
2. });
1. app.config(function	
  ($httpProvider)	
  {	
  
2. });
1. app.config(function	
  ($httpProvider)	
  {	
  
2. 	
  	
  $httpProvider.interceptors.push("nomeDoInterceptorA");	
  
3. });
1. app.config(function	
  ($httpProvider)	
  {	
  
2. 	
  	
  $httpProvider.interceptors.push("nomeDoInterceptorA");	
  
3. 	
  	
  $httpProvider.interceptors.push("nomeDoInterceptorB");	
  
4. });
1. app.config(function	
  ($httpProvider)	
  {	
  
2. 	
  	
  $httpProvider.interceptors.push("nomeDoInterceptorA");	
  
3. 	
  	
  $httpProvider.interceptors.push("nomeDoInterceptorB");	
  
4. 	
  	
  $httpProvider.interceptors.push("nomeDoInterceptorC");	
  
5. });
1. app.config(function	
  ($httpProvider)	
  {	
  
2. 	
  	
  $httpProvider.interceptors.push("nomeDoInterceptorA");	
  
3. 	
  	
  $httpProvider.interceptors.push("nomeDoInterceptorB");	
  
4. 	
  	
  $httpProvider.interceptors.push("nomeDoInterceptorC");	
  
5. });
Timestamp Interceptor	
  
Adiciona uma marcação contendo um
timestamp em todas as requisições.	
  
1. app.factory("timestampInterceptor",	
  function	
  ()	
  {	
  
2. });
1. app.factory("timestampInterceptor",	
  function	
  ()	
  {	
  
2. 	
  	
  return	
  {	
  
3. 	
  	
  };	
  
4. });
1. app.factory("timestampInterceptor",	
  function	
  ()	
  {	
  
2. 	
  	
  return	
  {	
  
3. 	
  	
  	
  	
  request:	
  function	
  (config)	
  {	
  
4. 	
  	
  	
  	
  	
  	
  return	
  config;	
  
5. 	
  	
  	
  	
  }	
  
6. 	
  	
  };	
  
7. });
1. app.factory("timestampInterceptor",	
  function	
  ()	
  {	
  
2. 	
  	
  return	
  {	
  
3. 	
  	
  	
  	
  request:	
  function	
  (config)	
  {	
  
4. 	
  	
  	
  	
  	
  	
  var	
  timestamp	
  =	
  new	
  Date().getTime();	
  
5. 	
  	
  	
  	
  	
  	
  config.url	
  =	
  config.url	
  +	
  "?timestamp="	
  +	
  timestamp;	
  
6. 	
  	
  	
  	
  	
  	
  return	
  config;	
  
7. 	
  	
  	
  	
  }	
  	
  
8. 	
  	
  };	
  
9. });
1. app.config(function	
  ($httpProvider)	
  {	
  
2. 	
  	
  $httpProvider.interceptors.push("timestampInterceptor");	
  
3. });
Error Interceptor	
  
Exibe a tela de erro padrão caso uma
requisição HTTP receba um status code 404
como resposta.	
  
1. app.factory("errorInterceptor",	
  function	
  ()	
  {	
  
2. });
1. app.factory("errorInterceptor",	
  function	
  ($q)	
  {	
  
2. 	
  	
  return	
  {	
  
3. 	
  	
  	
  	
  responseError:	
  function	
  (rejection)	
  {	
  
4. 	
  	
  	
  	
  	
  	
  return	
  $q.reject(rejection);	
  
5. 	
  	
  	
  	
  }	
  
6. 	
  	
  };	
  
7. });
1. app.factory("errorInterceptor",	
  function	
  ($q,	
  $location)	
  {	
  
2. 	
  	
  return	
  {	
  
3. 	
  	
  	
  	
  responseError:	
  function	
  (rejection)	
  {	
  
4. 	
  	
  	
  	
  	
  	
  if	
  (rejection.status	
  ==	
  404)	
  {	
  
5. 	
  	
  	
  	
  	
  	
  	
  	
  $location.path("/error");	
  
6. 	
  	
  	
  	
  	
  	
  }	
  
7. 	
  	
  	
  	
  	
  	
  return	
  $q.reject(rejection);	
  
8. 	
  	
  	
  	
  }	
  
9. 	
  	
  };	
  
10. });
1. app.config(function	
  ($httpProvider)	
  {	
  
2. 	
  	
  $httpProvider.interceptors.push("errorInterceptor");	
  
3. });
Loading Interceptor	
  
Exibe uma imagem de loading enquanto
tiver uma requisição em andamento.	
  
1. app.factory("loadingInterceptor",	
  function	
  ()	
  {	
  
2. });
1. app.factory("loadingInterceptor",	
  function	
  ($q)	
  {	
  
2. 	
  	
  return	
  {	
  
3. 	
  	
  	
  	
  request:	
  function	
  (config)	
  {	
  
4. 	
  	
  	
  	
  	
  	
  return	
  config;	
  
5. 	
  	
  	
  	
  },	
  
6. 	
  	
  	
  	
  requestError:	
  function	
  (rejection)	
  {	
  
7. 	
  	
  	
  	
  	
  	
  return	
  $q.reject(rejection);	
  
8. 	
  	
  	
  	
  },	
  
9. 	
  	
  	
  	
  response:	
  function	
  (response)	
  {	
  
10. 	
  	
  	
  	
  	
  	
  return	
  response;	
  
11. 	
  	
  	
  	
  },	
  
12. 	
  	
  	
  	
  responseError:	
  function	
  (rejection)	
  {	
  
13. 	
  	
  	
  	
  	
  	
  return	
  $q.reject(rejection);	
  
14. 	
  	
  	
  	
  }	
  
15. 	
  	
  };	
  
16. });
1. app.factory("loadingInterceptor",	
  function	
  ($q,	
  $rootScope)	
  {	
  
2. 	
  	
  return	
  {	
  
3. 	
  	
  	
  	
  request:	
  function	
  (config)	
  {	
  
4. 	
  	
  	
  	
  	
  	
  $rootScope.loading	
  =	
  true;	
  
5. 	
  	
  	
  	
  	
  	
  return	
  config;	
  
6. 	
  	
  	
  	
  },	
  
7. 	
  	
  	
  	
  requestError:	
  function	
  (rejection)	
  {	
  
8. 	
  	
  	
  	
  	
  	
  $rootScope.loading	
  =	
  false;	
  
9. 	
  	
  	
  	
  	
  	
  return	
  $q.reject(rejection);	
  
10. 	
  	
  	
  	
  },	
  
11. 	
  	
  	
  	
  response:	
  function	
  (response)	
  {	
  
12. 	
  	
  	
  	
  	
  	
  $rootScope.loading	
  =	
  false;	
  
13. 	
  	
  	
  	
  	
  	
  return	
  response;	
  
14. 	
  	
  	
  	
  },	
  
15. 	
  	
  	
  	
  responseError:	
  function	
  (rejection)	
  {	
  
16. 	
  	
  	
  	
  	
  	
  $rootScope.loading	
  =	
  false;	
  
17. 	
  	
  	
  	
  	
  	
  return	
  $q.reject(rejection);	
  
18. 	
  	
  	
  	
  }	
  
19. 	
  	
  };	
  
20. });
1. app.config(function	
  ($httpProvider)	
  {	
  
2. 	
  	
  $httpProvider.interceptors.push("loadingInterceptor");	
  
3. });
Rodrigo Branas	
  
Agile Code: http://www.agilecode.com.br
Twitter: @rodrigobranas
SlideShare: http://www.slideshare.com/rodrigobranas
YouTube: http://www.youtube.com/rodrigobranas
LinkedIn: http://br.linkedin.com/in/rodrigobranas
+Plus: https://plus.google.com/+RodrigoBranas
GitHub: http://www.github.com/rodrigobranas

More Related Content

What's hot

Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 SlidesSuraj Gupta
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Edureka!
 
Ajax (Asynchronous JavaScript and XML)
Ajax (Asynchronous JavaScript and XML)Ajax (Asynchronous JavaScript and XML)
Ajax (Asynchronous JavaScript and XML)Abdelouahed Abdou
 
OAuth2 and Spring Security
OAuth2 and Spring SecurityOAuth2 and Spring Security
OAuth2 and Spring SecurityOrest Ivasiv
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsStormpath
 
Django Framework and Application Structure
Django Framework and Application StructureDjango Framework and Application Structure
Django Framework and Application StructureSEONGTAEK OH
 
React Native Firebase Realtime Database + Authentication
React Native Firebase Realtime Database + AuthenticationReact Native Firebase Realtime Database + Authentication
React Native Firebase Realtime Database + AuthenticationKobkrit Viriyayudhakorn
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101Will Button
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Michel Schudel
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesVMware Tanzu
 
JWT-spring-boot-avancer.pdf
JWT-spring-boot-avancer.pdfJWT-spring-boot-avancer.pdf
JWT-spring-boot-avancer.pdfJaouad Assabbour
 
End to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaEnd to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaBabacar NIANG
 
Puppeteer can automate that! - Frontmania
Puppeteer can automate that! - FrontmaniaPuppeteer can automate that! - Frontmania
Puppeteer can automate that! - FrontmaniaÖnder Ceylan
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room LibraryReinvently
 

What's hot (20)

Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...Python Django tutorial | Getting Started With Django | Web Development With D...
Python Django tutorial | Getting Started With Django | Web Development With D...
 
Spring Boot 소개
Spring Boot 소개Spring Boot 소개
Spring Boot 소개
 
Ajax (Asynchronous JavaScript and XML)
Ajax (Asynchronous JavaScript and XML)Ajax (Asynchronous JavaScript and XML)
Ajax (Asynchronous JavaScript and XML)
 
OAuth2 and Spring Security
OAuth2 and Spring SecurityOAuth2 and Spring Security
OAuth2 and Spring Security
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 
Introduction à ajax
Introduction à ajaxIntroduction à ajax
Introduction à ajax
 
15. DateTime API.ppt
15. DateTime API.ppt15. DateTime API.ppt
15. DateTime API.ppt
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
Django Framework and Application Structure
Django Framework and Application StructureDjango Framework and Application Structure
Django Framework and Application Structure
 
React Native Firebase Realtime Database + Authentication
React Native Firebase Realtime Database + AuthenticationReact Native Firebase Realtime Database + Authentication
React Native Firebase Realtime Database + Authentication
 
Mongoose and MongoDB 101
Mongoose and MongoDB 101Mongoose and MongoDB 101
Mongoose and MongoDB 101
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition! Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
Battle Of The Microservice Frameworks: Micronaut versus Quarkus edition!
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
JWT-spring-boot-avancer.pdf
JWT-spring-boot-avancer.pdfJWT-spring-boot-avancer.pdf
JWT-spring-boot-avancer.pdf
 
End to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux SagaEnd to end todo list app with NestJs - Angular - Redux & Redux Saga
End to end todo list app with NestJs - Angular - Redux & Redux Saga
 
Puppeteer can automate that! - Frontmania
Puppeteer can automate that! - FrontmaniaPuppeteer can automate that! - Frontmania
Puppeteer can automate that! - Frontmania
 
Data Persistence in Android with Room Library
Data Persistence in Android with Room LibraryData Persistence in Android with Room Library
Data Persistence in Android with Room Library
 

Viewers also liked

Node.js - #7 - Core Modules - http - Parte 1 - Rodrigo Branas
Node.js - #7 - Core Modules - http - Parte 1 - Rodrigo BranasNode.js - #7 - Core Modules - http - Parte 1 - Rodrigo Branas
Node.js - #7 - Core Modules - http - Parte 1 - Rodrigo BranasRodrigo Branas
 
Criando serviços com AngularJS
Criando serviços com AngularJSCriando serviços com AngularJS
Criando serviços com AngularJSRodrigo Branas
 
Criando Filtros com AngularJS
Criando Filtros com AngularJSCriando Filtros com AngularJS
Criando Filtros com AngularJSRodrigo Branas
 
Criando aplicações Single-Page com AngularJS
Criando aplicações Single-Page com AngularJSCriando aplicações Single-Page com AngularJS
Criando aplicações Single-Page com AngularJSRodrigo Branas
 
A evolução do AngularJS
A evolução do AngularJSA evolução do AngularJS
A evolução do AngularJSRodrigo Branas
 
AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)Brian Swartzfager
 
Node.js - #5 - Process - Rodrigo Branas
Node.js - #5 - Process - Rodrigo BranasNode.js - #5 - Process - Rodrigo Branas
Node.js - #5 - Process - Rodrigo BranasRodrigo Branas
 
Node.js - #6 - Core Modules - net - Rodrigo Branas
Node.js - #6 - Core Modules - net - Rodrigo BranasNode.js - #6 - Core Modules - net - Rodrigo Branas
Node.js - #6 - Core Modules - net - Rodrigo BranasRodrigo Branas
 
Node.js - #2 - Sistema de Módulos - Rodrigo Branas
Node.js - #2 - Sistema de Módulos - Rodrigo BranasNode.js - #2 - Sistema de Módulos - Rodrigo Branas
Node.js - #2 - Sistema de Módulos - Rodrigo BranasRodrigo Branas
 
HTTP, JSON, REST e AJAX com AngularJS
HTTP, JSON, REST e AJAX com AngularJSHTTP, JSON, REST e AJAX com AngularJS
HTTP, JSON, REST e AJAX com AngularJSRodrigo Branas
 
Automação de Testes com AngularJS
Automação de Testes com AngularJSAutomação de Testes com AngularJS
Automação de Testes com AngularJSRodrigo Branas
 
AngularJS - 10 passos para aprender a criar suas directivas
AngularJS - 10 passos para aprender a criar suas directivasAngularJS - 10 passos para aprender a criar suas directivas
AngularJS - 10 passos para aprender a criar suas directivasJanderson Fernandes Cardoso
 
JavaScript - Expressões Regulares
JavaScript - Expressões RegularesJavaScript - Expressões Regulares
JavaScript - Expressões RegularesRodrigo Branas
 
Minicurso - Desenvolvendo aplicações web com JavaScript e AngularJS - Estácio...
Minicurso - Desenvolvendo aplicações web com JavaScript e AngularJS - Estácio...Minicurso - Desenvolvendo aplicações web com JavaScript e AngularJS - Estácio...
Minicurso - Desenvolvendo aplicações web com JavaScript e AngularJS - Estácio...Rodrigo Branas
 
Desvendando a linguagem JavaScript
Desvendando a linguagem JavaScriptDesvendando a linguagem JavaScript
Desvendando a linguagem JavaScriptRodrigo Branas
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide ServiceEyal Vardi
 

Viewers also liked (20)

Node.js - #7 - Core Modules - http - Parte 1 - Rodrigo Branas
Node.js - #7 - Core Modules - http - Parte 1 - Rodrigo BranasNode.js - #7 - Core Modules - http - Parte 1 - Rodrigo Branas
Node.js - #7 - Core Modules - http - Parte 1 - Rodrigo Branas
 
Criando serviços com AngularJS
Criando serviços com AngularJSCriando serviços com AngularJS
Criando serviços com AngularJS
 
Criando Filtros com AngularJS
Criando Filtros com AngularJSCriando Filtros com AngularJS
Criando Filtros com AngularJS
 
Scope AngularJS
Scope AngularJSScope AngularJS
Scope AngularJS
 
Criando aplicações Single-Page com AngularJS
Criando aplicações Single-Page com AngularJSCriando aplicações Single-Page com AngularJS
Criando aplicações Single-Page com AngularJS
 
A evolução do AngularJS
A evolução do AngularJSA evolução do AngularJS
A evolução do AngularJS
 
#2 - Git - DAG
#2 - Git - DAG#2 - Git - DAG
#2 - Git - DAG
 
AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)AngularJS $http Interceptors (Explanation and Examples)
AngularJS $http Interceptors (Explanation and Examples)
 
Node.js - #5 - Process - Rodrigo Branas
Node.js - #5 - Process - Rodrigo BranasNode.js - #5 - Process - Rodrigo Branas
Node.js - #5 - Process - Rodrigo Branas
 
Node.js - #6 - Core Modules - net - Rodrigo Branas
Node.js - #6 - Core Modules - net - Rodrigo BranasNode.js - #6 - Core Modules - net - Rodrigo Branas
Node.js - #6 - Core Modules - net - Rodrigo Branas
 
Node.js - #2 - Sistema de Módulos - Rodrigo Branas
Node.js - #2 - Sistema de Módulos - Rodrigo BranasNode.js - #2 - Sistema de Módulos - Rodrigo Branas
Node.js - #2 - Sistema de Módulos - Rodrigo Branas
 
HTTP, JSON, REST e AJAX com AngularJS
HTTP, JSON, REST e AJAX com AngularJSHTTP, JSON, REST e AJAX com AngularJS
HTTP, JSON, REST e AJAX com AngularJS
 
JavaScript - Date
JavaScript - DateJavaScript - Date
JavaScript - Date
 
Automação de Testes com AngularJS
Automação de Testes com AngularJSAutomação de Testes com AngularJS
Automação de Testes com AngularJS
 
AngularJS - 10 passos para aprender a criar suas directivas
AngularJS - 10 passos para aprender a criar suas directivasAngularJS - 10 passos para aprender a criar suas directivas
AngularJS - 10 passos para aprender a criar suas directivas
 
JavaScript - Expressões Regulares
JavaScript - Expressões RegularesJavaScript - Expressões Regulares
JavaScript - Expressões Regulares
 
Minicurso - Desenvolvendo aplicações web com JavaScript e AngularJS - Estácio...
Minicurso - Desenvolvendo aplicações web com JavaScript e AngularJS - Estácio...Minicurso - Desenvolvendo aplicações web com JavaScript e AngularJS - Estácio...
Minicurso - Desenvolvendo aplicações web com JavaScript e AngularJS - Estácio...
 
Desvendando a linguagem JavaScript
Desvendando a linguagem JavaScriptDesvendando a linguagem JavaScript
Desvendando a linguagem JavaScript
 
Grunt
GruntGrunt
Grunt
 
AngularJS $Provide Service
AngularJS $Provide ServiceAngularJS $Provide Service
AngularJS $Provide Service
 

More from Rodrigo Branas

Node.js - #4 - Timers - Rodrigo Branas
Node.js - #4 - Timers - Rodrigo BranasNode.js - #4 - Timers - Rodrigo Branas
Node.js - #4 - Timers - Rodrigo BranasRodrigo Branas
 
Node.js - #3 - Global Objects - Rodrigo Branas
Node.js - #3 - Global Objects - Rodrigo BranasNode.js - #3 - Global Objects - Rodrigo Branas
Node.js - #3 - Global Objects - Rodrigo BranasRodrigo Branas
 
Node.js - #1 - Introdução - Rodrigo Branas
Node.js - #1 - Introdução - Rodrigo BranasNode.js - #1 - Introdução - Rodrigo Branas
Node.js - #1 - Introdução - Rodrigo BranasRodrigo Branas
 
#6 - Git - Desfazendo as coisas
#6 - Git - Desfazendo as coisas#6 - Git - Desfazendo as coisas
#6 - Git - Desfazendo as coisasRodrigo Branas
 
#1 - Git - Introdução
#1 - Git - Introdução#1 - Git - Introdução
#1 - Git - IntroduçãoRodrigo Branas
 
#5 - Git - Contribuindo com um repositório remoto
#5 - Git - Contribuindo com um repositório remoto#5 - Git - Contribuindo com um repositório remoto
#5 - Git - Contribuindo com um repositório remotoRodrigo Branas
 
#3 - Git - Branching e Merging
#3 - Git - Branching e Merging#3 - Git - Branching e Merging
#3 - Git - Branching e MergingRodrigo Branas
 
Técnicas de Refactoring
Técnicas de RefactoringTécnicas de Refactoring
Técnicas de RefactoringRodrigo Branas
 
Test-Driven Development com JavaScript, Jasmine Karma
Test-Driven Development com JavaScript, Jasmine  KarmaTest-Driven Development com JavaScript, Jasmine  Karma
Test-Driven Development com JavaScript, Jasmine KarmaRodrigo Branas
 

More from Rodrigo Branas (13)

Clean Architecture
Clean ArchitectureClean Architecture
Clean Architecture
 
Node.js - #4 - Timers - Rodrigo Branas
Node.js - #4 - Timers - Rodrigo BranasNode.js - #4 - Timers - Rodrigo Branas
Node.js - #4 - Timers - Rodrigo Branas
 
Node.js - #3 - Global Objects - Rodrigo Branas
Node.js - #3 - Global Objects - Rodrigo BranasNode.js - #3 - Global Objects - Rodrigo Branas
Node.js - #3 - Global Objects - Rodrigo Branas
 
Node.js - #1 - Introdução - Rodrigo Branas
Node.js - #1 - Introdução - Rodrigo BranasNode.js - #1 - Introdução - Rodrigo Branas
Node.js - #1 - Introdução - Rodrigo Branas
 
#6 - Git - Desfazendo as coisas
#6 - Git - Desfazendo as coisas#6 - Git - Desfazendo as coisas
#6 - Git - Desfazendo as coisas
 
#1 - Git - Introdução
#1 - Git - Introdução#1 - Git - Introdução
#1 - Git - Introdução
 
#5 - Git - Contribuindo com um repositório remoto
#5 - Git - Contribuindo com um repositório remoto#5 - Git - Contribuindo com um repositório remoto
#5 - Git - Contribuindo com um repositório remoto
 
#4 - Git - Stash
#4 - Git - Stash#4 - Git - Stash
#4 - Git - Stash
 
#3 - Git - Branching e Merging
#3 - Git - Branching e Merging#3 - Git - Branching e Merging
#3 - Git - Branching e Merging
 
Técnicas de Refactoring
Técnicas de RefactoringTécnicas de Refactoring
Técnicas de Refactoring
 
Selenium - WebDriver
Selenium - WebDriverSelenium - WebDriver
Selenium - WebDriver
 
Test-Driven Development com JavaScript, Jasmine Karma
Test-Driven Development com JavaScript, Jasmine  KarmaTest-Driven Development com JavaScript, Jasmine  Karma
Test-Driven Development com JavaScript, Jasmine Karma
 
Bower
BowerBower
Bower
 

HTTP Interceptors com AngularJS

  • 1. Rodrigo Branas – @rodrigobranas - http://www.agilecode.com.br Interceptors com AngularJS
  • 2.
  • 3. Um interceptor é um tipo de serviço que permite a interceptação das requisições e respostas do serviço $http.
  • 4. 1. app.factory("nomeDoInterceptorA",  function  ($q)  {   2.    return  {   3.        request:  function  (config)  {   4.            return  config;   5.        },   6.        requestError:  function  (rejection)  {   7.            return  $q.reject(rejection);   8.        },   9.        response:  function  (response)  {   10.            return  response;   11.        },   12.        responseError:  function  (rejection)  {   13.            return  $q.reject(rejection);   14.        }   15.    };   16. });
  • 5. Configurando o interceptor O serviço $http possui um array de interceptors que podem ser configurados na inicialização da aplicação.  
  • 8. 1. app.config(function  ($httpProvider)  {   2.    $httpProvider.interceptors.push("nomeDoInterceptorA");   3. });
  • 9. 1. app.config(function  ($httpProvider)  {   2.    $httpProvider.interceptors.push("nomeDoInterceptorA");   3.    $httpProvider.interceptors.push("nomeDoInterceptorB");   4. });
  • 10. 1. app.config(function  ($httpProvider)  {   2.    $httpProvider.interceptors.push("nomeDoInterceptorA");   3.    $httpProvider.interceptors.push("nomeDoInterceptorB");   4.    $httpProvider.interceptors.push("nomeDoInterceptorC");   5. });
  • 11. 1. app.config(function  ($httpProvider)  {   2.    $httpProvider.interceptors.push("nomeDoInterceptorA");   3.    $httpProvider.interceptors.push("nomeDoInterceptorB");   4.    $httpProvider.interceptors.push("nomeDoInterceptorC");   5. });
  • 12. Timestamp Interceptor   Adiciona uma marcação contendo um timestamp em todas as requisições.  
  • 14. 1. app.factory("timestampInterceptor",  function  ()  {   2.    return  {   3.    };   4. });
  • 15. 1. app.factory("timestampInterceptor",  function  ()  {   2.    return  {   3.        request:  function  (config)  {   4.            return  config;   5.        }   6.    };   7. });
  • 16. 1. app.factory("timestampInterceptor",  function  ()  {   2.    return  {   3.        request:  function  (config)  {   4.            var  timestamp  =  new  Date().getTime();   5.            config.url  =  config.url  +  "?timestamp="  +  timestamp;   6.            return  config;   7.        }     8.    };   9. });
  • 17. 1. app.config(function  ($httpProvider)  {   2.    $httpProvider.interceptors.push("timestampInterceptor");   3. });
  • 18. Error Interceptor   Exibe a tela de erro padrão caso uma requisição HTTP receba um status code 404 como resposta.  
  • 20. 1. app.factory("errorInterceptor",  function  ($q)  {   2.    return  {   3.        responseError:  function  (rejection)  {   4.            return  $q.reject(rejection);   5.        }   6.    };   7. });
  • 21. 1. app.factory("errorInterceptor",  function  ($q,  $location)  {   2.    return  {   3.        responseError:  function  (rejection)  {   4.            if  (rejection.status  ==  404)  {   5.                $location.path("/error");   6.            }   7.            return  $q.reject(rejection);   8.        }   9.    };   10. });
  • 22. 1. app.config(function  ($httpProvider)  {   2.    $httpProvider.interceptors.push("errorInterceptor");   3. });
  • 23. Loading Interceptor   Exibe uma imagem de loading enquanto tiver uma requisição em andamento.  
  • 25. 1. app.factory("loadingInterceptor",  function  ($q)  {   2.    return  {   3.        request:  function  (config)  {   4.            return  config;   5.        },   6.        requestError:  function  (rejection)  {   7.            return  $q.reject(rejection);   8.        },   9.        response:  function  (response)  {   10.            return  response;   11.        },   12.        responseError:  function  (rejection)  {   13.            return  $q.reject(rejection);   14.        }   15.    };   16. });
  • 26. 1. app.factory("loadingInterceptor",  function  ($q,  $rootScope)  {   2.    return  {   3.        request:  function  (config)  {   4.            $rootScope.loading  =  true;   5.            return  config;   6.        },   7.        requestError:  function  (rejection)  {   8.            $rootScope.loading  =  false;   9.            return  $q.reject(rejection);   10.        },   11.        response:  function  (response)  {   12.            $rootScope.loading  =  false;   13.            return  response;   14.        },   15.        responseError:  function  (rejection)  {   16.            $rootScope.loading  =  false;   17.            return  $q.reject(rejection);   18.        }   19.    };   20. });
  • 27. 1. app.config(function  ($httpProvider)  {   2.    $httpProvider.interceptors.push("loadingInterceptor");   3. });
  • 28. Rodrigo Branas   Agile Code: http://www.agilecode.com.br Twitter: @rodrigobranas SlideShare: http://www.slideshare.com/rodrigobranas YouTube: http://www.youtube.com/rodrigobranas LinkedIn: http://br.linkedin.com/in/rodrigobranas +Plus: https://plus.google.com/+RodrigoBranas GitHub: http://www.github.com/rodrigobranas

Editor's Notes

  1. Qual é a sua obra?
  2. Qual é a sua obra?
  3. Desmotivado
  4. Desmotivado
  5. Motivação
  6. Desmotivação
  7. Desmotivação
  8. Desmotivação
  9. Desmotivação
  10. Desmotivação
  11. Desmotivação
  12. Desmotivação
  13. Desmotivação
  14. Desmotivação
  15. Desmotivação
  16. Desmotivação
  17. Desmotivação
  18. Desmotivação
  19. Desmotivação
  20. Desmotivação
  21. Desmotivação
  22. Desmotivação
  23. Desmotivação
  24. Desmotivação
  25. Desmotivação
  26. Desmotivação
  27. Desmotivação
  28. Desmotivação
  29. Desmotivação
  30. Desmotivação
  31. Desmotivação