我有一個http全局服務,它被稱爲所有服務;所以我可以通過實例進行最佳管理;錯誤,警報,變量等。處理HTTP全局服務錯誤角4.3,handleError,401,0等,攔截器,jwt,頭
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);
}
}
客戶-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'));
}
}
前角4.3我有可觀的,我可以有捕獲錯誤,並在組件中的全局服務,子服務中拋出一個observable。現在,它不工作,我不知道如何管理漁獲物,並處理好與觀測
誤差在新的角度指南: https://angular.io/guide/http#error-handling
只是管理誤差以簡單的方式,
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}`);
}
}
});
現在管理這個的正確方法是什麼?