Angular HTTP 响应数据处理:自动替换 En 后缀属性值
以下是符合题意的 JavaScript 函数:
function replaceEn(obj) {
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
obj.forEach((item) => {
replaceEn(item);
});
} else {
Object.keys(obj).forEach((key) => {
replaceEn(obj[key]);
if (key.endsWith('En') && obj[key] !== '') {
const originKey = key.substring(0, key.length - 2);
if (obj[originKey] !== undefined) {
obj[originKey] = obj[key];
}
}
});
}
}
return obj;
}
以下是使用 Angular 的 HttpInterceptor 模块来对所有 HTTP 返回进行处理的代码:
import { Injectable } from '@angular/core';
import {
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpEvent,
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
@Injectable()
export class EnInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
return next.handle(req).pipe(
map((response) => {
if (response.body) {
response = response.clone({ body: replaceEn(response.body) });
}
return response;
})
);
}
}
function replaceEn(obj) {
if (typeof obj === 'object') {
if (Array.isArray(obj)) {
obj.forEach((item) => {
replaceEn(item);
});
} else {
Object.keys(obj).forEach((key) => {
replaceEn(obj[key]);
if (key.endsWith('En') && obj[key] !== '') {
const originKey = key.substring(0, key.length - 2);
if (obj[originKey] !== undefined) {
obj[originKey] = obj[key];
}
}
});
}
}
return obj;
}
在 Angular 的 AppModule 中注册 EnInterceptor:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { EnInterceptor } from './en.interceptor';
@NgModule({
imports: [BrowserModule, HttpClientModule],
declarations: [AppComponent],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: EnInterceptor,
multi: true,
},
],
bootstrap: [AppComponent],
})
export class AppModule {}
原文地址: https://www.cveoy.top/t/topic/nWaJ 著作权归作者所有。请勿转载和采集!