[英]Using rxjs/ajax interceptor in React
我在 React 中使用 rxjs/ajax,所以我需要添加一个拦截器来处理 header 和响应(全局错误),有什么建议吗?
谢谢
您可以创建一个更高阶的 function 来产生一个具有拦截功能的 ajax function 并将此实例导出以备后用。
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()
这是处理错误、标头和基数 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);
});
}
})
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.