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?

Thank you

Upvotes: 0

Views: 939

Answers (2)

Fan Cheung
Fan Cheung

Reputation: 11380

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

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()

Upvotes: 1

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

            }

        })
    );
}

Upvotes: 0

Related Questions