I have my own angular 5 project, I have an HTTP interceptor Component for adding auth in the header for all request, and also I have a service to call custom server API. when I use HTTP, my rest service works fine (of course I added cors filter in my tomcats's web.xml) but my HTTP interceptor Component does not catch it, but when I use httpClient it goes throw HTTP interceptor Component but the server response is "No 'Access-Control-Allow-Origin' header is present on the requested resource". would you please help me?
import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';
import { Http, Headers, Response, RequestOptions, RequestMethod } from
'@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { HttpClient, HttpHeaders } from '@angular/common/http';
const API_URL = environment.apiUrl;
@Injectable()
export class RestService {
constructor(private http: HttpClient) { }
private handleError (error: Response | any) {
console.error('ApiService::handleError', error);
return Observable.throw(error);
}
public getAll(input: any, url: string): Observable<any> {
return this.http
//.get('http://httpbin.org/headers')
.post(API_URL + url, input)
.map(response => {
const returnedData = response;
return returnedData;
})
.catch(this.handleError);
}
}
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders }
from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
@Injectable()
export class HttpinterceptorComponent implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
console.log('intercepted request ... ');
const headers = new HttpHeaders({
'sessionId': 'token 123',
'Content-Type': 'application/json'
});
// Clone the request to add the new header.
const authReq = req.clone({headers});
console.log('Sending request with new header now ...');
// send the newly created request
return next.handle(authReq)
.catch((error, caught) => {
// intercept the respons error and displace it to the console
console.log('Error Occurred');
console.log(error);
// return the error to the method that called it
return Observable.throw(error);
}) as any;
}
}