拦截每个 http 调用 ES6 方法



我想用Angular编写可以拦截所有ajax调用的可注入服务。基本上在ajax开始之前和完成后。我能够通过这个代码片段来实现。但是我能够使用 es5 语法来实现它。如何通过扩展文件编号:3中显示的XMLHttpRequest来执行相同的操作?

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

也许是这样的?

class HttpInterceptor extends XMLHttpRequest {
  onreadystatechange = () => {
    switch (this.readyState) {
      case 1:
        this.ajaxStart();
        break;
      case 4:
        this.ajaxStop();
        break;
    }
  }
  ajaxStart() {
    console.log('operation started.');
  }
  ajaxStop() {
    console.log('operation completed.');
  }
}
const interceptor = new HttpInterceptor();
interceptor.open('GET', 'https://developer.mozilla.org/');
interceptor.send();

最新更新