CodingAleCR / http_interceptor

A lightweight, simple plugin that allows you to intercept request and response objects and modify them if desired.
MIT License
134 stars 67 forks source link

How to use as a reusable service ? #7

Closed Standaa closed 4 years ago

Standaa commented 4 years ago

Hello, I am looking to build an HttpInterceptor Service in dart, that would act the same way as a service I have built in Angular 2 :

@Injectable({
  providedIn: 'root'
})
export class InterceptorService implements HttpInterceptor {
  constructor(private auth: AuthService) { }
   intercept(
     req: HttpRequest<any>,
     next: HttpHandler
   ): Observable<HttpEvent<any>> [...]
}

In Angular 2 Ts, I am injecting this service in a CoreModule, and can therefore intercept all requests from all services in that module :

@NgModule({
  declarations: [
  ],
  imports: [
  ],
  providers: [
    {
       provide: HTTP_INTERCEPTORS,
       useClass: InterceptorService,
       multi: true
    },
 ]

By the examples, it seems the service has to be provided with each Http request. Is there a way to achieve the pattern I am describing above ?

Many thanks.

CodingAleCR commented 4 years ago

As of right now, you cannot do a service that intercepts all http requests because those are from a different plugin, dart's own: http package.

What this plugin allows you to do, however, is to do an implementation of a customized Client which allows you to intercept all requests that go through said client as per the Using interceptors with Client section specifies. You could also potentially make a global instance of said interceptor but you would have to be on the lookout to close out connections when done.

However, if you really need something like this you could try a more powerful library like the dio package.