gpt4 book ai didi

angular - 使用 http 全局服务 angular 4.3、handleError、401、0 等、拦截器、jwt、 header 处理错误

转载 作者:太空狗 更新时间:2023-10-29 17:44:31 25 4
gpt4 key购买 nike

我有一个为所有服务调用的 http 全局服务;所以我可以最好地以身作则;错误、警报、变量等

客户服务.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);
}
}

全局服务.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'));
}
}

在 angular 4.3 之前,我有 observables ,我可以捕获错误,并在全局服务、子服务和组件中抛出一个 observable。现在它不工作了,我不确定如何管理 catch,以及如何处理 observables 的错误

在新的 Angular 指南中: 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}`);
}
}
});

现在管理这个的正确方法是什么?

最佳答案

仍然有可观察对象,您基本上可以保留现有的组件代码。您只需更改服务代码即可使用新的 HttpClient

这是我的新服务:

import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';

import { IProduct } from './product';

@Injectable()
export class ProductService {
private _productUrl = './api/products/products.json';

constructor(private _http: HttpClient) { }

getProducts(): Observable<IProduct[]> {
return this._http.get<IProduct[]>(this._productUrl)
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}

private handleError(err: HttpErrorResponse) {
// in a real world app, we may send the server to some remote logging infrastructure
// instead of just logging it to the console
let errorMessage = '';
if (err.error instanceof Error) {
// A client-side or network error occurred. Handle it accordingly.
errorMessage = `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,
errorMessage = `Server returned code: ${err.status}, error message is: ${err.message}`;
}
console.error(errorMessage);
return Observable.throw(errorMessage);
}
}

这是我的组件中的方法,它基本上没有变化:

ngOnInit(): void {
this._productService.getProducts()
.subscribe(products => this.products = products,
error => this.errorMessage = <any>error);
}

关于angular - 使用 http 全局服务 angular 4.3、handleError、401、0 等、拦截器、jwt、 header 处理错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45512701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com