什么是在angular2中相当于httpinterceptor?

在angularjs中,我们有http拦截器

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

与我们可以挂钩到所有的http调用,并显示或隐藏加载栏,做日志等。

angular2中的等价物是什么?

正如@Günter指出的那样,没有办法注册拦截器。 你需要扩展Http类,并把你的拦截处理放在HTTP调用的周围

首先你可以创build一个扩展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 }); } } 

并按照如下所述进行注册:

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

在调用目标方法之前,可以添加requestrequestErrortypes。

对于response之一,您需要将一些asynchronous处理插入到现有的处理链中。 这取决于你的需要,但你可以使用Observable的运算符(如flatMap )。

最后,对于responseError ,你需要在目标调用上调用catch操作符。 这样,当响应发生错误时,您会收到通知。

这个链接可以帮助你:

  • 使用rxjs处理刷新令牌
  • Angular 2 – 如何在全球范围内获取Observable.throw

更新

Angular 4.3.0中引入的新HttpClient模块支持拦截器https://github.com/angular/angular/compare/4.3.0-rc.0…4.3.0

feat(普通):新的HttpClient API HttpClient是现有的Angular HTTP API的一个演变,它存在于一个单独的包(@ angular / common / http)中。 这种结构可以确保现有的代码库可以慢慢迁移到新的API。

新的API在传统API的人体工程学和function方面显着改善。 新function的部分列表包括:

  • 键入同步响应正文访问,包括对JSON正文types的支持
  • JSON是一个假设的默认值,不再需要明确的parsing
  • 拦截器允许将中间件逻辑插入到stream水线中
  • 不可变的请求/响应对象
  • 请求上传和响应下载的进度事件
  • 请求后validation和基于刷新的testing框架

原版的

Angular2没有(还)拦截器。 您可以改为扩展HttpXHRBackendBaseRequestOptions或任何其他相关的类(至less在TypeScript和Dart(不知道普通的JS)。

也可以看看

  • RFC:Http拦截器和变换器
  • 引入拦截机制
  • Angular2中的拦截器
  • Angular2 – 为每个请求设置标题

在这个仓库中有一个Http @ angular / core-like服务的实现: https : //github.com/voliva/angular2-interceptors

您只需在引导程序中声明该服务的提供者,添加您所需的任何拦截器,并且它将适用于所有组件。

 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] }) 

您可以创build自己的自定义HTTP类,并使用rxjs主题服务重用您的自定义Http类,并在自定义类中实现您的行为。

使用包含一些rxjs主题的“HttpSubjectService”实现您的自定义Http类。

 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(); }); } } 

自定义模块注册你的CustomHttp类 – 在这里你用自己的CustomHttp实现覆盖Angular的默认Http实现。

 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() { } } 

现在我们需要HttpSubjectService实现,当我们使用“next”语句调用rxjs主题时,我们可以SubScribe到我们的rxjs主题。

 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); } } 

要调用您的自定义实现,我们需要在“app.component.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"; } 

使用Angular 4.3.1版本,现在有一个名为HttpInterceptor的接口。

这里是链接到文档: https : //angular.io/api/common/http/HttpInterceptor

这是一个实现示例。


这将是拦截器类的实现。

基本上写作其他服务:

 @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() }); } } } }); } } 

然后,因为你会像普通的服务一样对待它,所以你必须在你的应用程序模块的提供者中添加这一行:

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

希望它可以帮助。

现在Angular 4.3支持Http拦截器。 看看如何使用它们: https : //ryanchenkie.com/angular-authentication-using-the-http-client-and-http-interceptors

我已经发布了以下节点模块的拦截器。 我们为内部目的创build了这个模块最后我们在npm包pipe理器中发布npm install angular2-resource-and-ajax-interceptor https://www.npmjs.com/package/angular2-resource-and-ajax-interceptor

正如@squadwuschel指出的,正在进行的工作是将这个function放到@ angular / http中。 这将是一个新的HttpClient API的forms。

有关更多详细信息和当前状态,请参阅https://github.com/angular/angular/pull/17143

Angular2不支持httpinterceptor like angular1

这是在angular2中使用httpinterceptor的好例子。

https://github.com/NgSculptor/ng2HttpInterceptor

从Teradata尝试共价键 ,他们提供了很多angular度和angular度材料的扩展。

检查HTTP部分,它在Angular和RESTService中提供缺less的http拦截器(类似于restangular)。

我已经在我的示例中通过共价HTTP实现了JWT令牌authentication,请在这里查看。

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

阅读我的开发笔记, 通过IHttpInterceptor处理基于令牌的身份validation 。