Home > OS >  Using rxjs/ajax interceptor in React
Using rxjs/ajax interceptor in React

Time:02-22

I use rxjs/ajax in React so I need to add an interceptor to handle header and response (global errors), is there any suggestion?

Thank you

CodePudding user response:

You can create a higher order function to produce an ajax function with intercept feature and export this instance for later use.

const withIntercept=(interceptor)=> {

return (param)=>ajax(param).pipe(
  map(interceptor),
  catchError(error => {
    console.log('error: ', error);
    return of(error);
  })
);
}

// usage 
export const ajaxWithInterceptor=withIntercept=(param=>....do something with param)

CodePudding user response:

This is a sample for get request that handle errors, headers and base url for other methods we can copy and paste.

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);
                });

            }

        })
    );
}
  • Related