我想在Angular中编写可注入的服务,它可以拦截所有的ajax调用。基本上在ajaxStart之前和之后完成。我能够通过这个代码片段来实现。但是我能够使用es5语法实现它。如何通过扩展XMLHttpRequest
来完成相同的操作,如文件编号:3所示?拦截每个http调用ES6方法
1)HTTP-interceptor.ts
import { Injectable, Component, OnInit } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
interface AjaxRequest {
url?: string;
requestCount?: number;
method?: string;
}
interface AjaxResponse {
url?: string;
requestCount?: number;
response?: string;
}
@Injectable()
export class HttpInterceptor {
public ajaxStart = new BehaviorSubject<AjaxRequest>({});
public ajaxStop = new BehaviorSubject<AjaxResponse>({});
constructor() {
this.bootstrapAjaxInterceptor();
}
private bootstrapAjaxInterceptor() {
const _self = this;
const originalOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (xhrMethod, requestUrl) {
_self.ajaxStart.next(requestUrl);
this.addEventListener('readystatechange', xhr => {
_self.ajaxStop.next(this.responseURL);
}, false);
originalOpen.apply(this, arguments);
};
}
}
2)APP-component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
constructor(private httpInterceptor: HttpInterceptor) { }
ngOnInit() {
this.httpInterceptor.ajaxStart.subscribe(url => {
console.log('ajaxStart : ', url);
});
this.httpInterceptor.ajaxStop.subscribe(url => {
console.log('ajaxStop : ', url);
});
}
}
3)的http-interceptor.ts
@Injectable()
export class HttpInterceptor extends XMLHttpRequest {
open(xhrMethod, requestUrl) {
// Equivalent to XMLHttpRequest.prototype.open
// Now how to handle `readystatechange`
}
ajaxStart() { }
ajaxStop() { }
}
感谢@Bahrampour的更正。如果你觉得这是个好问题。你可以赞成吗? –