私はすべてのサービスに対して呼び出されるhttpグローバルサービスを持っています。だから私は最高の例で管理することができます。エラー、アラート、変数など。角度4.3前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'));
}
}
私は私が持っている可能性があり、観測していましたエラーをキャッチし、コンポーネント内のグローバルサービス(子サービス内)にオブザーバブルをスローします。今では働いていないと私はキャッチを管理し、新しい角度ガイドで観測
でエラーを処理するかどうかはわかりません:、 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}`);
}
}
});
今これを適切に管理する方法は何ですか?