KhodeN
2/15/2018 - 11:03 AM

api-url.interceptor.ts

import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Inject, Injectable } from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { API_URL } from 'st/constants';


@Injectable()
export class ApiUrlInterceptor implements HttpInterceptor {
  constructor(@Inject(API_URL) private _apiUrl: string) {
  }

  public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // Обращение к статичным вещам, а не к API
    if ( /^\/assets\//.test(req.url) ) {
      return next.handle(req);
    }

    // Обращение к API
    const url = this._apiUrl + req.url;

    return next.handle(req.clone({url}));
  }
}