tratamento de erro com o serviço global http angular 4.3, handleError, 401, 0, etc, interceptor, jwt, headers
Eu tenho um serviço globals http chamado para todos os serviços; para que eu possa gerenciar melhor pelo exemplo; erros, alertas, variáveis, etc.
customers.service.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);
}
}
customers-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 do angular 4.3 eu tinha observáveis, eu poderia pegar o erro e lançar um observável no serviço global, no serviço filho, no componente. Agora não está funcionando e não sei como gerenciar capturas e lidar com erros com observáveis
No novo guia angular:https://angular.io/guide/http#error-handling
basta gerenciar o erro de uma maneira simples,
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}`);
}
}
});
Qual é o caminho certo para gerenciar isso agora?