Je voulais écrire un service injectable en Angulaire qui peut intercepter tous les appels ajax. Fondamentalement avant ajaxStart et après fini. Je suis capable de réaliser par ce code-snippets. Mais je suis capable de le faire en utilisant la syntaxe es5. Comment puis-je faire la même chose en prolongeant XMLHttpRequest
qui est montré dans le fichier n ° 3?Intercepter chaque http appelle une approche 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() { }
}
Merci @Bahrampour pour les corrections. Si vous sentez que c'est une bonne question. Pourriez-vous l'augmenter? –