[英]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.