0

In my library, I export a http interceptor.

Currently to activate the interceptor, the user must use the following code:

import { provideNgProgressHttp, progressInterceptor } from 'ngx-progressbar/http';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(
      withInterceptors([progressInterceptor])
    ),
    provideNgProgressHttp()
  ]
});

I would like to avoid the withInterceptors([progressInterceptor]) part, and make it internally when user provide provideNgProgressHttp(). is this possible?

Expected usage:

import { provideNgProgressHttp } from 'ngx-progressbar/http';

bootstrapApplication(AppComponent, {
  providers: [
    provideHttpClient(),
    provideNgProgressHttp()
  ]
});

Here is my code:

The interceptor function

export function progressInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
  return next(req).pipe(
    finalize(() => {
      // Some code
    })
  );
}

The provider function

export const NG_PROGRESS_HTTP_CONFIG: InjectionToken<NgProgressHttpConfig> = new InjectionToken<NgProgressHttpConfig>('ngProgressHttpConfig');

export function provideNgProgressHttp(config?: NgProgressHttpConfig): Provider {
  return [
    {
      provide: NG_PROGRESS_HTTP_CONFIG,
      useValue: config
    }
  ];
}
2
  • Hi, Yes it should be possible. You have to modify your provideNgProgressHttp so that it returns a list of providers that include both the existing NG_PROGRESS_HTTP_CONFIG provider and interceptor provider. Could look something like this : export function provideNgProgressHttp(config?: NgProgressHttpConfig): Provider[] { return [ { provide: NG_PROGRESS_HTTP_CONFIG, useValue: config }, { provide: HTTP_INTERCEPTORS, useFactory: () => progressInterceptor, multi: true } ]; } Commented Aug 14, 2024 at 6:34
  • @LaughByte Better not to write an answer as comment. but no I don't think this would work this is an interceptor function Commented Aug 15, 2024 at 1:01

1 Answer 1

0

This is not possible and this is by design. The HTTP_INTERCEPTORS token is not exposed.

This was a deliberate design choice of the new API; interceptors are sensitive to ordering and the registration of the HTTP services to actually consider those interceptors, so the API was designed such that both ordering and the registration is determined in a single place.

What you should do in your case, you should have a function that returns a list of interceptors, and it should be passed directly to provideHttpClient().

provideHttpClient(withInterceptors([...ngProgressHttpInterceptors()]))),
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.