2017-10-20 125 views
0

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

感謝@Bahrampour的更正。如果你覺得這是個好問題。你可以贊成嗎? –

回答

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

無法通過DI角度初始化或通過const const Interceptor = new HttpInterceptor();它拋出ERROR TypeError:無法構造'XMLHttpRequest':請使用'new'操作符,此DOM對象構造函數不能被調用作爲一個功能' –

+0

嗨@dork你的回答給了我一點點提示,如此upvoted你,但仍然在尋找正確的解決方案。如果您覺得這是一個很好的問題,請快速提出我的問題,以便快速獲得答案。 –