I am using angular 2 and I want to intercept all responses and redirect user to login page if session is expired.
I came across This Question, and I have been following This Answer.
Everything compiles correctly. By inspecting in debugger I can see that constructor
has been called, but super.request
has never been reached.
Here is my extended HTTP
Module
import { Injectable } from '@angular/core';
import { Request, XHRBackend, RequestOptions, Response, Http, RequestOptionsArgs, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
@Injectable()
export class AuthenticatedHttpService extends Http {
constructor(backend:XHRBackend, defaultOptions:RequestOptions) {
super(backend, defaultOptions);
}
request(url:string | Request, options?:RequestOptionsArgs):Observable<Response> {
return super.request(url, options).catch((error:Response) => {
if ((error.status === 401 || error.status === 403) && (window.location.href.match(/\?/g) || []).length < 2) {
console.log('The authentication session expires or the user is not authorised. Force refresh of the current page.');
}
return Observable.throw(error);
});
}
}
In app.module.ts
I have provider defined as
...
providers: [{
provide: HttpModule,
useClass: AuthenticatedHttpService
}, SessionService, MyService]
...
And in MyService
I have
import {Injectable} from "@angular/core";
import {Http, Response, Headers, RequestOptions} from "@angular/http";
import {Observable} from "rxjs/Rx";
import { environment } from '../../../environments/environment';
@Injectable()
export class MyService {
apiUrl:string = environment.apiUrl;
constructor(private http:Http) {
}
getData() {
let headers = new Headers();
headers.append('x-access-token', 'my-token');
return this.http
.get(this.apiUrl + '/getData', {headers: headers}
).map((res:Response) => res.json());
}
}
Can anyone point me in a right direction what am I doing wrong?