I have a http globalservice that it's called for all services; so i can manage best by example; errors, alerts, variables,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'));
}
}
before angular 4.3 I had observables , i could have catch for the error, and throw an observable in global service, in child service, in the component. Now it's not working and i'm not sure how to manage catch, and handle error with observables
In the new angular guide: https://angular.io/guide/http#error-handling
just manage error in a simple way,
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}`);
}
}
});
what is the right way to manage now this ?
You do still have observables and you can basically leave your existing component code as is. All you need to change is the service code to use the new
HttpClient
.Here is my new service:
And here is the method in my component, which was basically unchanged:
I've found finally a solution, errors are objects, so before angular 4.3 the error object was a Response, now its HttpErrorResponse, anyway we get objects, so we can ask for properties. Most of functions don't consider the error status 0, o nothing when the server is not working, or when your interceptor in angular 4.3 or anything you did in your error manage don't produce correct status.
the final solution i've found is just simply ask for object properties from error object, and I can have define messages errors in the case i don't want show backend errors for known errors.
look for environment.ts file ( angular-cli create this file ):
then handle error for the global service can be:
in your interceptor
if you make an error in your interceptor by example with the code below, the handleError will work anyway:
Define a strict type for the error scenario as below,
Use the
handleError
common method to handle by modifying as below,