I am currently working on an application which uses AOT in production. The problem is that when using Httpinterceptors in dev mode using JIT mode, everything works fine. But when building it for production, all the interceptors stops working. I tried using factories when providing the interceptors, still can't figure out the proper way to do it. for example:
core.module.ts
export function authInterceptorFactory(injector: Injector) {
return new ArticleInterceptor(injector);
}
@NgModule({
declarations: [],
imports: [CommonModule],
exports: [],
providers: [
{
provide: HTTP_INTERCEPTORS,
// useClass: ArticleInterceptor,
useFactory: authInterceptorFactory,
multi: true,
deps: [Injector]
}
]
})
article.interceptor.ts
@Injectable()
export class ArticleInterceptor implements HttpInterceptor {
private isRefreshing = false;
private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(
null
);
constructor(private injector: Injector) {}
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
if (req.url.startsWith(environment.ARTICLE.API_URL)) {
if (
this.injector.get(TokenStorageService).getArticleToken() !== undefined
) {
req = this.addToken(
req,
this.injector.get(TokenStorageService).getArticleToken()
);
}
return next.handle(req).pipe(
catchError(error => {
if (error instanceof HttpErrorResponse && error.status === 401) {
return this.handle401Error(req, next);
} else {
return throwError(error);
}
})
);
}
return next.handle(req);
}
private addToken(request: HttpRequest<any>, token: string) {
let newParams = new HttpParams({ fromString: request.params.toString() });
newParams = newParams.append('access_token', token);
return request.clone({
params: newParams
});
}
private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
if (!this.isRefreshing) {
this.isRefreshing = true;
this.refreshTokenSubject.next(null);
return this.injector
.get(AuthenticationService)
.loginArticles()
.pipe(
switchMap((token: any) => {
this.isRefreshing = false;
this.refreshTokenSubject.next(token.access_token);
return next.handle(this.addToken(request, token.access_token));
})
);
} else {
return this.refreshTokenSubject.pipe(
filter(token => token != null),
take(1),
switchMap(token => {
return next.handle(this.addToken(request, token));
})
);
}
}
}
So, How to properly use HttpInterceptors with AOT enabled angular project, or is there any alternatives to it optimized for AOT?
[EDIT]: I found the problem. An old version of "ngx-auth" had a problem with AOT that breaks interceptors (I think it was related to a problem in declaring HttpInterceptor). Updating it fixed the problem.