import { Injectable } from '@angular/core';
import {HttpRequest,HttpResponse, HttpErrorResponse, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import { Router } from '@angular/router';
import { SharedService } from './shared.service';
@Injectable({
  providedIn: 'root'
})
export class ResponceInterceptService {

  constructor(private router: Router, private auth: SharedService) { }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    
    return next.handle(request).do((event: HttpEvent<any>) => {
      if (event instanceof HttpResponse) {
        console.log('token not expire');
      }
    }, (err: any) => {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          // redirect to the login route
          this.auth.collectFailedRequest(request);
          this.router.navigate['/login'];
          // or show a modal
        }
      }
    });
  }

}
