我试图在Angular应用中调用API后正确处理错误。
I already tried this link “Cannot read property message of null” when reading error status code from http response in Angular 8 but the structure used there is a little bit different of what I have in my app.
I have a HttpService
class with all CRUD operations:
export class HttpService {
constructor(private http: HttpClient) { }
public get<T>(apiUrl: string, headers: HttpHeaders) {
return new Promise<T>((resolve, reject) => {
this.http
.get(apiUrl, { headers: headers })
.subscribe(
(res) => resolve(res as unknown as T),
error => reject(error));
});
}
public post<T>(apiUrl: string, body: any, headers: HttpHeaders) {
return new Promise<T>((resolve, reject) => {
this.http
.post(apiUrl, body, { headers: headers })
.subscribe(
(res) => resolve(res as T),
error => reject(error));
});
}
public put(apiUrl: string, body: any, headers: HttpHeaders) {
return new Promise<boolean>((resolve, reject) => {
this.http
.put(apiUrl, body, { headers: headers })
.subscribe(
() => resolve(true),
error => reject(error));
});
}
public delete(apiUrl: string, headers: HttpHeaders) {
return new Promise<boolean>((resolve, reject) => {
this.http
.delete(apiUrl, { headers: headers })
.subscribe(
() => resolve(true),
error => reject(error));
});
}
}
And then I have a ApiService
class where I store all the API calls:
export class ApiService {
constructor(private http: HttpService) {
}
//#region HEADERS
private getRequestHeaders(): HttpHeaders {
const headers = new HttpHeaders();
headers.append('Access-Control-Allow-Origin', '*');
headers.append('Content-Type', 'application/json; charset=utf-8');
return headers;
}
//#endregion
//#region COMPANY METHODS
getCompanyPaginated(take: number, skip: number, search: string): Promise<any> {
return this.http.get<any[]>(`${AppSettings.BaseAPI}/Company/Paginated?take=${take}&skip=${skip}&search=${search}`, this.getRequestHeaders());
}
//#endregion COMPANY METHODS
}
And finally here's where I call the method to get the companies in my company.component.ts
:
getCompany(pageNumber?: number, search?: string) {
let skip = !pageNumber ? 0 : (pageNumber * this.pageSize);
this.apiService.getCompanyPaginated(this.pageSize, skip, (search || ''))
.then(response => {
this.isLoading = false;
if (response) {
this.length = response.totalItems;
this.dataSource.data = response.data;
}
}).catch(error => {
this.isLoading = false;
console.log(error);
});
}
And the problem is where I access the error
object in the catch
function. In the browser console I got this message:
TypeError:无法读取null的属性“ message”
我要开始正确看到错误对象有什么想法?