简体   繁体   English

在 React 中使用 rxjs/ajax 拦截器

[英]Using rxjs/ajax interceptor in React

I use rxjs/ajax in React so I need to add an interceptor to handle header and response (global errors), is there any suggestion?我在 React 中使用 rxjs/ajax,所以我需要添加一个拦截器来处理 header 和响应(全局错误),有什么建议吗?

Thank you谢谢

You can create a higher order function to produce an ajax function with intercept feature and export this instance for later use.您可以创建一个更高阶的 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()

This is a sample for get request that handle errors, headers and base url for other methods we can copy and paste.这是处理错误、标头和基数 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM