I'm using ngx-translate and now I would like to add a LoadingInterceptor. So an HTTPInterceptor that shows a LoadingSpinner when an API request is made.
I am already using a token interceptor. But when I install the LoadingInterceptor, ngx-translate no longer works.
Here is my loading.interceptor.ts
import { Observable } from 'rxjs';
// import { LoadingService } from './../../../services/loading.service';
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
@Injectable()
export class LoadingInterceptor implements HttpInterceptor {
// Liste von Requests
private requests: HttpRequest<any>[] = [];
constructor() {}
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('detect request', request.url);
return new Observable(observer => {
});
}
}
And this is my app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
// Translate
import { TranslateModule, TranslateLoader, TranslateService } from '@ngx-translate/core';
import {TranslateHttpLoader} from '@ngx-translate/http-loader';
// Interceptors
import { HTTP_INTERCEPTORS, HttpClient, HttpClientModule } from '@angular/common/http';
import { TokenInterceptor } from './interceptors/token.interceptor';
import { LoadingInterceptor } from './interceptors/loading.interceptor';
// tslint:disable-next-line:typedef
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule,
TranslateModule.forRoot({
defaultLanguage: 'de',
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient]
}
})
],
providers: [
[
{
provide: HTTP_INTERCEPTORS,
useClass: LoadingInterceptor,
multi: true
},
{
provide: HTTP_INTERCEPTORS,
useClass: TokenInterceptor,
multi: true
}
],
TranslateService,
],
bootstrap: [AppComponent]
})
export class AppModule { }
This is my html tag with the variable to be translated:
<span>{{ 'TEST' | translate }}</span>
And this is the de.json file from my i18n folder:
{
"TEST": "Hello world"
}
I don't get an error message, the variable to be translated is simply no longer displayed. Unless I comment out the LoadingInterceptor in the app.module.ts.
intercept
method should always return the reponse in some way, your interceptor is simply returning a new Observable, which obviously doesn't contain the translation anymore (ngx-translate gets its translations from .json, which is also intercepted by interceptors).
public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('detect request', request.url);
return next.handle(request);
}
This interceptor simply returns the original request without modifying it (No-op)