0
votes

I am trying to port the code of an Angular 2 app to Angular Dart, so that I can reuse the business logic in Flutter. My app makes use of HttpInterceptors for Error handling and server authorization.

In typescript I would inject a simple service :

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

But the Dart API does not seem to have an HttpInterceptor class. Does one have to extend the HttpClient class in order to do so ?

I have looked at this S.O question but it dates back from 5 years ago, the way to do it has probably changed quite a bit in the meantime.

1

1 Answers

0
votes

Turns out there are a couple ways you can achieve this in Angular Dart / Flutter.

Some third party libraries built on top of dart http provide convenience methods for Http interception (DIO, Http Interceptor). However, both handle interception at the client level.

I decided to go with the Dart Http library, using the recommended method :

class UserAgentClient extends http.BaseClient {
  final String userAgent;
  final http.Client _inner;

  UserAgentClient(this.userAgent, this._inner);

  Future<StreamedResponse> send(BaseRequest request) {
    request.headers['user-agent'] = userAgent;
    return _inner.send(request);
  }
}