I am currently working with TypeScript and Angular 5.0. I have defined the structure of my backend response in the following interface:
export interface JSONResponse {
error?: {
code: number,
message: string
};
data?: {};
}
The method in my service to retrieve data from the server is as follows:
httpGet(url: string, httpParams: HttpParams) {
return new Promise((resolve, reject) => {
this.http.get<LoginResponse>(url, {params: httpParams})
.subscribe(res => {
resolve(res.data);
}, err => {
// handle HTTP GET errors here
console.log(err);
});
});
}
This is how the component utilizes the service to display the template:
buttonClicked(event) {
this.myService.httpGet('myAPIurl', someRequestParams)
.then((data) => {
this.myData = data;
}, (err) => {
console.log(err);
});
}
Where should I implement the logic for checking errors in the response from the backend?
In other words, if the property data
exists, the response was successful and I can process the data accordingly. If the property error
exists, I need to inform the user about the error with the corresponding code/message.