Я использовал httpintercept для обработки 401 (неавторизованной) ошибки в службах данных в моем проекте angular 6. Но служба httpintercept не принимает в моем проекте.
Это мой файл intercept.services.ts
export class InterceptService implements HttpInterceptor {
constructor(private authService: AuthService) { }
// intercept request and add token
intercept(request: HttpRequest<any>, next: HttpHandler):Observable<HttpEvent<any>> {
// modify request
request = request.clone({
setHeaders: {
Authorization: `Bearer ${JSON.parse(localStorage.getItem('currentUser')).token}`
}
});
console.log("----request----");
console.log(request);
console.log("--- end of request---");
return next.handle(request)
.pipe(
tap(event => {
if (event instanceof HttpResponse) {
console.log(" all looks good");
// http response status code
console.log(event.status);
}
}, error => {
// http response status code
console.log("----response----");
console.error("status code:");
console.error(error.status);
console.error(error.message);
console.log("--- end of response---");
})
)
};
}
Это моя общая страница service.ts
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
import {Http, Response,Headers ,RequestOptions } from "@angular/http";
import { HttpModule} from '@angular/http';
import { map } from 'rxjs/operators';
import { Router } from '@angular/router';
const API_URL = '//api path';
@Injectable({
providedIn: 'root'
})
export class DataService {
ctrURL:any;
postData:any;
ajaxdata:any;
constructor(private http:Http,private router: Router) { }
get_data(url,auth=true){
//......url : url path......
//....auth : true api auth required,false no api required....
var get_url = API_URL + url;
var headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
if(auth==true){
var localStore = JSON.parse(localStorage.getItem('currentUser'));
headers.append("Authorization", "Bearer " + localStore.token);
}
let options = new RequestOptions({ headers });
return this.http.get(get_url, options) .pipe((map(res => res.json())));
}
}