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

最佳答案

也许是这样的吗?

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

关于javascript - 拦截每个http调用ES6方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46842922/

10-13 01:10