About HTTP interceptors


#1

How can i use HTTP interceptors with nativescript-angular?
In Web projects with angular, interceptors work very well.
But with nativescript-angular, HTTP requests can not be intercepted as expected.
Could anyone help?

Interceptor

import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';
import { environment } from '~/environments/environment';

@Injectable()
export class ApiProxyInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler)
      : Observable<HttpEvent<any>> {

    console.log('xxxx intercepted!')
    const {headers} = req;

    if (headers.has('X-No-API-Proxy') && headers.get('X-No-API-Proxy') === 'yes') {
      const _headers = headers.delete('X-No-API-Prefix');
      return next.handle(req.clone({headers: _headers}));
    }

    const urlPrefix = environment.backend;
    const proxyReq = req.clone({
      url: `${urlPrefix}/${req.url}`
    });

    return next.handle(proxyReq);
  }

}

Interceptor providers

import { Provider } from '@angular/core';
import { HTTP_INTERCEPTORS } from '@angular/common/http';

import { ApiProxyInterceptor } from './api-proxy/api-proxy.service';

export const interceptorProviders = [
  {
    provide: HTTP_INTERCEPTORS,
    useClass: ApiProxyInterceptor,
    multi: true
  }
];

Shared module to register interceptors

import { NgModule, ModuleWithProviders } from '@angular/core';
import { ApiModule } from '../api/api.module';

import { interceptorProviders } from './interceptors';

@NgModule({
  imports: [ApiModule],
  declarations: [],
  exports: [ApiModule]
})
export class SharedModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: SharedModule,
      providers: [
        ...interceptorProviders
      ]
    }
  }
}

App module to import interceptor providers

import { NgModule, NgModuleFactoryLoader, NO_ERRORS_SCHEMA, Injector } from '@angular/core';
import { NativeScriptModule } from 'nativescript-angular/nativescript.module';
import { NativeScriptHttpClientModule } from 'nativescript-angular/http-client';
import { SharedModule as AppSharedModule } from './business/public/shared/shared.module'

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

export let injector: Injector;

@NgModule({
  bootstrap: [
    AppComponent
  ],
  imports: [
    NativeScriptModule,
    NativeScriptHttpClientModule,
    AppSharedModule.forRoot(),
    AppRoutingModule,
  ],
  declarations: [
    AppComponent,
  ],
  schemas: [
    NO_ERRORS_SCHEMA
  ]
})
export class AppModule {
  constructor(private _injector: Injector) {
    injector = _injector;
  }
}

#2

Solved! It’s my fault.
Forgot to ‘subscribe’ the HTTP request, as a result, the ‘cold’ Observable didn’t trigger any request. HTTP interceptors can work well with nativescript-angular.