How To Display Data Using Angular 4 Interceptors

738 views Asked by At

I'm new to Angular 4 interceptors and I'm trying to implement this in my application. All i wanted to do is if i have an 404 error or like if token expires it would navigate me to the login page. Also, my problem is that I how would i display my data in the html? I've already commented out my previous working example without the new http interceptor. Anyone who can help me display my data and when error occurs redirect me to the login page? I've posted my code below. Thanks.

news.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpRequest} from '@angular/common/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/of';

@Injectable()
export class NewsService {
  newslist: any;

  constructor(private httpClient: HttpClient) {}

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

 getAllNews() {

    // if(this.newslist != null) {
    //   return Observable.of(this.newslist);
    // } 

    // else {
      const authToken = localStorage.getItem('auth_token'); 
      const headers = new HttpHeaders() 
      .set('Content-Type', 'application/json') 
      .set('Authorization', `Bearer ${authToken}`);

    //   return this.httpClient
    //     .get('http://sample.com/news/', 
    //       { headers: headers })
    //     .map((response => response))
    //     .do(newslist => this.newslist = newslist)
    //     .catch(e => {
    //         if (e.status === 401) {
    //             return Observable.throw('Unauthorized');

    //         }

    //     });
    // }

    const req = new HttpRequest('GET', 'http://sample.com/news/', {reportProgress: true,  headers: headers  } )
    return this.httpClient.request(req);
  }

  getNews(id: number) { 
    return this.getAllNews().map((data:any)=> data.data.data.find(news => news.id === id)) 
  }

}

news.interceptor.ts

import { HttpInterceptor, HttpHandler, HttpRequest, HttpEvent } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { NewsService } from './news.service';


@Injectable()
export class NewsInterceptor implements HttpInterceptor {
    constructor(private newsService: NewsService){}
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>{
        console.log("Intercepted!", req);
        const copiedReq = req.clone({headers: req.headers});
        return next.handle(req);
    }
}
0

There are 0 answers