I am in the process of transitioning from basic HTML and JavaScript to Angular for my web application. This means I need to rewrite my JavaScript Ajax calls to my PHP server controller in Angular syntax. As a beginner in writing Ajax calls with jQuery and new to Angular 8, I am seeking guidance on how to approach this task.
Below is the jQuery Ajax code that I need to convert into Angular TypeScript:
$.ajax({
data: DATA,
url: '../upgrade/controller/app_validateManager.php',
dataType: 'json',
type: 'POST',
beforeSend: function(x) {
if (x && x.overrideMimeType) {
x.overrideMimeType("application/json;charset=UTF-8");
}
},
success: function(data){
console.log("works")
if (data.status == 0)
{
alert('Response >> '+data.datr[0]);
// window.location.href = redirectLink;
}
else{
console.log(prockey + " error")
console.log(data)
for(i=0;i<data.errpos.length;i++){
$('#err'+data.errpos[i]).innerHtml = data.errmsg[i]
}
}
},
error: function (xhr, status, errorThrown) {
//Here the status code can be retrieved like;
xhr.status;
//The message added to Response object in Controller can be retrieved as following.
xhr.responseText;
}
});
My attempt at converting the jQuery Ajax call into an Angular service and component:
// Angular Service code:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json;charset=UTF-8"',
})
};
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
// A client-side or network error occurred. Handle it accordingly.
console.error('An error occurred:', error.error.message);
} else {
// The backend returned an unsuccessful response code.
// The response body may contain clues as to what went wrong,
console.error(
`Backend returned code ${error.status}, ` +
`body was: ${error.error}`);
}
// return an observable with a user-facing error message
return throwError(
'Something bad happened; please try again later.');
}
ajaxEngine(DATA: PostData): Observable<PostData> {
console.log(DATA);
return this.httpClient.post<PostData>(this.phpurl, DATA, httpOptions)
.pipe(
retry(3), // retry a failed request up to 3 times
catchError(this.handleError)
);
}
// Angular Component code:
this.mainService.ajaxEngine(new PostData(newDATA))
.subscribe(
data => {
console.log('works' + data);
this.postData = data;
},
error => {
console.log(error);
}
);