gpt4 book ai didi

javascript - 拦截每个http调用的一个ES6方法

转载 作者:行者123 更新时间:2023-12-03 03:14:04 24 4
gpt4 key购买 nike

我想在 Angular 中编写可注入(inject)服务,它可以拦截所有 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) 应用程序组件.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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com