拦截每个http调用ES6方法

时间:2017-10-20 05:36:52

标签: javascript angularjs dependency-injection ecmascript-6

我想在Angular中编写可注射服务,它可以拦截所有的ajax调用。基本上是在ajaxStart之前和之后完成的。我能够通过这个代码片段来实现。但我能够使用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() { }
}

1 个答案:

答案 0 :(得分:1)

也许是这样的?

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