我在React中使用rxjs/ajax,所以我需要添加一个拦截器来处理标头和响应(全局错误),有什么建议吗?
谢谢你
您可以创建一个高阶函数来生成具有拦截功能的ajax函数,并导出此实例以供以后使用。
const withIntercept=(preInterceptor, postInterceptor) => {
return (param) =>ajax(preInterceptor(param)).pipe(
map(postInterceptor),
catchError(error => {
console.log('error: ', error);
return of(error);
})
);
}
// usage
export const ajaxWithInterceptor=withIntercept=(
param =>{ param.header={..new header }; return param },
res => do something with response...)
ajaxWithInterceptor({url:xxx,header:xxx,body:xxxx,method:"post" }).subscribe()
这是一个 get 请求示例,用于处理错误、标头和基本 url,以便我们可以复制和粘贴其他方法。
const baseURL = "http://example.com/api/";
export const getAjax = (endpoint, headers = null) => {
return ajax.get(baseURL + endpoint, headers).pipe(
catchError(error => {
if (error.status === 404) {
return of(error);
} else {
return new Promise((resolve, reject) => {
reject(error);
});
}
})
);
}
我分享了我用可用的 rxjs 工具构建的拦截器