¿Qué es httpinterceptor equivalente en angular2?


En angularjs, tenemos http interceptor

$httpProvider.interceptors.push('myHttpInterceptor');

Con el que podemos engancharnos a todas las llamadas http, y mostrar u ocultar barras de carga, hacer logging, etc..

¿Cuál es el equivalente en angular2?

Author: Pardeep Jain, 2016-02-19

10 answers

Como lo señaló @Günter, no hay forma de registrar interceptores. Necesita extender la clase Http y poner su procesamiento de interceptación alrededor de llamadas HTTP

Primero puedes crear una clase que extienda el Http:

@Injectable()
export class CustomHttp extends Http {
  constructor(backend: ConnectionBackend, defaultOptions: RequestOptions) {
    super(backend, defaultOptions);
  }

  request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
    console.log('request...');
    return super.request(url, options).catch(res => {
      // do something
    });        
  }

  get(url: string, options?: RequestOptionsArgs): Observable<Response> {
    console.log('get...');
    return super.get(url, options).catch(res => {
      // do something
    });
  }
}

Y registrarlo como se describe a continuación:

bootstrap(AppComponent, [HTTP_PROVIDERS,
    new Provider(Http, {
      useFactory: (backend: XHRBackend, defaultOptions: RequestOptions) => new CustomHttp(backend, defaultOptions),
      deps: [XHRBackend, RequestOptions]
  })
]);

Los tipos request y requestError podrían añadirse antes de llamar a los métodos de destino.

Para el response, debe conectar algún procesamiento asíncrono al procesamiento existente cadena. Esto depende de su necesidad, pero puede usar operadores (como flatMap) de Observable.

Finalmente para el responseError, necesita llamar al operador catch en la llamada de destino. De esta manera, se le notificará cuando se produzca un error en la respuesta.

Estos enlaces podrían ayudarte:

 63
Author: Thierry Templier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-05 10:12:00

Actualización

El nuevo módulo HttpClient introducido en Angular 4.3.0 soporta interceptores https://github.com/angular/angular/compare/4.3.0-rc.0...4.3.0

Feat (common): nueva API HttpClient HttpClient es una evolución de la API HTTP Angular existente, que existe junto a ella en un separado paquete, @ angular / common / http. Esta estructura garantiza que los las bases de código pueden migrar lentamente a la nueva API.

La nueva API mejora significativamente la ergonomía y las características de la API heredada. Una lista parcial de nuevas características incluye:

  • Acceso al cuerpo de respuesta síncrona, incluido el soporte para tipos de cuerpo JSON
  • JSON es un valor predeterminado asumido y ya no necesita ser analizado explícitamente
  • Los interceptores permiten insertar lógica de middleware en la canalización
  • Objetos de solicitud/respuesta inmutables
  • Eventos de progreso tanto para la carga de solicitudes como para respuesta descargar
  • Marco de pruebas basado en verificación posterior a la solicitud y descarga

Original

Angular2 no tiene (todavía) interceptores. En su lugar, puede extender Http, XHRBackend, BaseRequestOptions o cualquiera de las otras clases involucradas (al menos en TypeScript y Dart (no sé sobre JS simple).

Véase también

 16
Author: Günter Zöchbauer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-19 07:34:02

Hay una implementación para un servicio similar a Http @ angular / core en este repositorio: https://github.com/voliva/angular2-interceptors

Simplemente declare el proveedor para ese servicio en bootstrap, agregando cualquier interceptor que necesite, y estará disponible para todos los componentes.

import { provideInterceptorService } from 'ng2-interceptors';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...,
    HttpModule
  ],
  providers: [
    MyHttpInterceptor,
    provideInterceptorService([
      MyHttpInterceptor,
      /* Add other interceptors here, like "new ServerURLInterceptor()" or
         just "ServerURLInterceptor" if it has a provider */
    ])
  ],
  bootstrap: [AppComponent]
})
 12
Author: olivarra1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-28 13:50:18

DEPRICATED DESDE Angular 4.3 (HttpInterCeptors están de vuelta en 4.3)

Puede crear su propia clase HTTP personalizada y usar rxjs Subject Service para reutilizar su clase Http personalizada e implementar sus comportamientos en una clase personalizada.

Implementación de su Clase Http Personalizada con "HttpSubjectService" que contiene algunos temas rxjs.

import { Injectable } from '@angular/core';
import { Http, ConnectionBackend, Request, RequestOptions, RequestOptionsArgs, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';


import { HttpSubjectService } from './httpSubject.service';


@Injectable()
export class CustomHttp extends Http {
   constructor(backend: ConnectionBackend, defaultOptions: RequestOptions, private httpSubjectService: HttpSubjectService) {
       super(backend, defaultOptions);

       //Prevent Ajax Request Caching for Internet Explorer
       defaultOptions.headers.append("Cache-control", "no-cache");
       defaultOptions.headers.append("Cache-control", "no-store");
       defaultOptions.headers.append("Pragma", "no-cache");
       defaultOptions.headers.append("Expires", "0");
   }

   request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
       //request Start;
       this.httpSubjectService.addSpinner();
       return super.request(url, options).map(res => {
           //Successful Response;
           this.httpSubjectService.addNotification(res.json());
           return res;
       })
           .catch((err) => {
               //Error Response.
               this.httpSubjectService.removeSpinner();
               this.httpSubjectService.removeOverlay();

               if (err.status === 400 || err.status === 422) {
                   this.httpSubjectService.addHttp403(err);
                   return Observable.throw(err);
               } else if (err.status === 500) {
                   this.httpSubjectService.addHttp500(err);
                   return Observable.throw(err);
               } else {
                   return Observable.empty();
               }
           })
           .finally(() => {
               //After the request;
               this.httpSubjectService.removeSpinner();
           });
   }
}

Módulo personalizado para registrar su clase CustomHttp: aquí sobrescribe la implementación Http predeterminada de Angular con su implementación CustomHttp propia.

import { NgModule, ValueProvider } from '@angular/core';
import { HttpModule, Http, XHRBackend, RequestOptions } from '@angular/http';

//Custom Http
import { HttpSubjectService } from './httpSubject.service';
import { CustomHttp } from './customHttp';

@NgModule({
    imports: [ ],
    providers: [
        HttpSubjectService,
        {
           provide: Http, useFactory: (backend: XHRBackend, defaultOptions: RequestOptions, httpSubjectService: HttpSubjectService) => {
                return new CustomHttp(backend, defaultOptions, httpSubjectService);
            },
            deps: [XHRBackend, RequestOptions, HttpSubjectService]
        }
    ]
})
export class CustomHttpCoreModule {

    constructor() { }
}

Ahora necesitamos la implementación HttpSubjectService donde podemos suscribirnos a nuestros sujetos rxjs cuando se les llama con la instrucción "next".

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class HttpSubjectService {
    //https://github.com/ReactiveX/rxjs/blob/master/doc/subject.md
    //In our app.component.ts class we will subscribe to this Subjects
    public notificationSubject = new Subject();
    public http403Subject = new Subject();
    public http500Subject = new Subject();
    public overlaySubject = new Subject();
    public spinnerSubject = new Subject();

    constructor() { }

    //some Example methods we call in our CustomHttp Class
    public addNotification(resultJson: any): void {
        this.notificationSubject.next(resultJson);
    }

    public addHttp403(result: any): void {
        this.http403Subject.next(result);
    }

    public addHttp500(result: any): void {
        this.http500Subject.next(result);
    }

    public removeOverlay(): void {
        this.overlaySubject.next(0);
    }

    public addSpinner(): void {
        this.spinnerSubject.next(1);
    }

    public removeSpinner(): void {
        this.spinnerSubject.next(-1);
    }
}

Para llamar a sus Implementaciones personalizadas necesitamos suscribirse a los Temas en el ejemplo "aplicación.componente.ts".

import { Component } from '@angular/core';
import { HttpSubjectService } from "../HttpInterception/httpSubject.service";
import { Homeservice } from "../HttpServices/home.service";

@Component({
    selector: 'app',
    templateUrl: './app.component.html',
})
export class AppComponent {
    private locals: AppLocalsModel = new AppLocalsModel();

    constructor(private httpSubjectService : HttpSubjectService, private homeService : Homeservice) {}

    ngOnInit(): void {
        this.notifications();
        this.httpRedirects();
        this.spinner();
        this.overlay();
    }

    public loadServiceData(): void {
        this.homeService.getCurrentUsername()
            .subscribe(result => {
                this.locals.username = result;
            });
    }

    private overlay(): void {
        this.httpSubjectService.overlaySubject.subscribe({
            next: () => {
              console.log("Call Overlay Service");
            }
        });
    }

    private spinner(): void {
        this.httpSubjectService.spinnerSubject.subscribe({
            next: (value: number) => {
              console.log("Call Spinner Service");
            }
        });
    }

    private notifications(): void {
        this.httpSubjectService.notificationSubject.subscribe({
            next: (json: any) => {
                console.log("Call Notification Service");
            }
        });
    }

    private httpRedirects(): void {
        this.httpSubjectService.http500Subject.subscribe({
            next: (error: any) => {
                console.log("Navigate to Error Page");
            }
        });

        this.httpSubjectService.http403Subject.subscribe({
            next: (error: any) => {
                console.log("Navigate to Not Authorized Page");
            }
        });
    }
}


class AppLocalsModel {
    public username : string = "noch nicht abgefragt";
}

DESDE ANGULAR 4.3 puedes Usar Interceptores

En Angular 4.3 tienes interceptores nativos donde puedes implementar tus propias cosas como una redirección para error de servidor 500

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class SxpHttp500Interceptor implements HttpInterceptor {

  constructor(public router: Router) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return next.handle(req).do(evt => { }).catch(err => {
          if (err["status"]) {
              if (err.status === 500) {
                  this.router.navigate(['/serverError', { fehler: JSON.stringify(err) }]);
              }
          }
          return Observable.throw(err);
      });
  }
}

Necesita registrar esto en su módulo principal en la matriz de proveedores

import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { Router } from '@angular/router';
import { SxpHttp500Interceptor } from "./sxpHttp500.interceptor";
 ....

providers: [
    {
        provide: HTTP_INTERCEPTORS, useFactory: (router: Router) => { return new SxpHttp500Interceptor(router) },
        multi: true,
        deps: [Router]
    }
]
 10
Author: squadwuschel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-17 13:41:11

Con la versión Angular 4.3.1, ahora hay una interfaz llamada HttpInterceptor.

Aquí está el enlace a los documentos: https://angular.io/api/common/http/HttpInterceptor

Aquí hay una muestra de implementación.


Esta sería la implementación de la clase interceptor.

Se escribe básicamente como cualquier otro servicio:

@Injectable()
export class ExceptionsInterceptor implements HttpInterceptor {
    constructor(
        private logger: Logger,
        private exceptionsService: ExceptionsService,
        private notificationsService: NotificationsService
    ) { }
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        return next.handle(request)
            .do((event) => {
                // Do nothing here, manage only errors
            }, (err: HttpErrorResponse) => {
                if (!this.exceptionsService.excludeCodes.includes(err.status)) {
                    if (!(err.status === 400 && err.error['_validations'])) {
                        this.logger.error(err);
                        if (!this.notificationsService.hasNotificationData(err.status)) {
                            this.notificationsService.addNotification({ text: err.message, type: MessageColorType.error, data: err.status, uid: UniqueIdUtility.generateId() });
                        }
                    }
                }
            });
    }
}

Entonces, ya que tratarás esto como un servicio normal, debes agregar esta línea dentro del módulo de tu aplicación proveedores:

{ provide: HTTP_INTERCEPTORS, useClass: ExceptionsInterceptor, multi: true }

Espero que pueda ayudar.

 6
Author: Caius,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-09 07:41:05

Angular 4.3 ahora soporta Http interceptor out-of-the-box. Échale un vistazo a cómo usarlos: https://ryanchenkie.com/angular-authentication-using-the-http-client-and-http-interceptors

 2
Author: Martino Bordin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-19 07:30:50

He lanzado interceptor con el siguiente módulo de nodo. Creamos este módulo para nuestro propósito interno y finalmente lo lanzamos en npm package manager npm install angular2-resource-and-ajax-interceptor https://www.npmjs.com/package/angular2-resource-and-ajax-interceptor

 0
Author: Rajan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-09 06:17:34

Como señaló @squadwuschel, se está trabajando para obtener esta funcionalidad en @angular/http. Esto será en forma de una nueva API HttpClient.

Véase https://github.com/angular/angular/pull/17143 para más detalles y estado actual.

 0
Author: rdukeshier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-03 21:54:18

Angular2 no soporta httpinterceptor como angular1

Aquí está el ejemplo impresionante del uso de httpinterceptor en angular2.

Https://github.com/NgSculptor/ng2HttpInterceptor

 0
Author: Er. Bahuguna Goyal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-23 06:11:56

Pruebe Covalente de Teradata, que proporciona un montón de extensiones para Angular y Angular Material.

Compruebe HTTP parte, proporciona el interceptor http que falta en Angular y RESTService(similar a restangular).

He implementado la autenticación de token JWT a través de HTTP covalente en mi muestra, verifique aqui.

Https://github.com/hantsy/angular2-material-sample/blob/master/src/app/core/auth-http-interceptor.ts

Lea mis notas de desarrollo para ello, Maneje la autenticación basada en tokens a través de IHttpInterceptor.

 0
Author: Hantsy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-14 13:10:22