error de manejo con http global service angular 4.3, handleError, 401, 0, etc., interceptor, jwt, encabezados
Tengo un servicio global de http que se llama para todos los servicios; entonces puedo manejar mejor con el ejemplo; errores, alertas, variables, etc.
clientes.servicios.ts
export class CustomersService {
childUrl = environment.apiUrl + 'customers';
constructor(
private http: HttpClient,
private globalService: GlobalService
) {
}
public get(childUrl) {
return this.globalService.get(this.childUrl)
.catch((res: Response) => this.handleError(res));
}
...
private handleError(err) {
return Observable.throw(err);
}
}
global.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';
@Injectable()
export class GlobalService {
url: string,
constructor(private http: HttpClient) {
this.headers = new HttpHeaders()
.set('Content-Type', 'application/json; charset=utf-8')
.set('Accept', 'application/json');
}
public prepare ( vars ) {
this.url = environment.apiUrl + vars.childUrl;
}
public get( childUrl) {
this.prepare ({childUrl} );
return this.http.get(this.url, { headers: this.headers, observe: 'response'})
.catch((res: Response) => this.handleError(res);
}
private handleError(err) {
return Observable.throw(err);
}
}
clientes-list.component
export class CustomersListComponent implements OnInit {
public customers: Array <any>;
constructor (private customersService: CustomersService ) { }
ngOnInit() {
this.get();
}
private get(): void {
this.customerService
.get()
.subscribe((data) => {this.customers = data.data; console.log(data) },
error => console.log(error),
() => console.log('Get all Items complete'));
}
}
antes del angular 4.3 tenía observables, podría haber detectado el error y arrojar un observable en el servicio global, en el servicio secundario, en el componente. Ahora no funciona y no estoy seguro de cómo administrar la captura y manejar el error con observables
En la nueva guía angular:https://angular.io/guide/http#error-handling
solo administra el error de una manera simple,
http
.get<ItemsResponse>('/api/items')
.subscribe(
data => {...},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
console.log('An error occurred:', err.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
}
}
});
¿Cuál es la forma correcta de gestionar esto ahora?