What is the best way to implement Angular 8's version of jQuery's ajax functionality?

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);
      }
    );

Answer №1

Utilize the power of ajax from rxjs/ajax to generate an observable for your ajax requests. By subscribing to it, you can easily access received data and efficiently handle any errors that may arise. For further information, check out this link: Learn more about rxjs ajax here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieving information from a secondary window

Currently, I am working on a project and have come across an issue. Please take a look at the following code snippet: <iframe name="stus" id="stus" style="display:none;"></iframe> <form name="water" id="water" method="post" autocomplete="of ...

Using Angular Material to link a constant within an HTML file

I have set up my constants in the following way: constants.ts export const Constants = Object.freeze({ ACCEPTED_LEADS_TO_CALL: "Accepted Leads to Call", RECOMMENDED_CALL_LIST: "Recommended Call List" }); This makes it easy to refere ...

Browsing through a jQuery JSON object in Chrome reveals a dynamic reshuffling of its order

Jquery + rails 4 Within the json_data instance, there is data with key-value pairs. The key is an integer ID and the value is an object containing data. However, when attempting to iterate over this data using the jQuery $.each function, the results are s ...

Eliminating Body Tag Margin in Angular 4: A Step-by-Step Guide

In the Angular 4 project, the app.component.html file does not include a body tag that can be styled to eliminate the padding associated with the body tag. https://i.sstatic.net/5QS9x.jpg An attempt was made in the app.component.css file to remove the ma ...

Tips on validating file types using jQuery's Ajax function

I am new to web programming and need help validating and uploading a file. I want to have 2 conditions: if the file type doesn't match, show an alert saying "Invalid file"; second condition, if the file is empty or matches, insert data. However, if th ...

Stripping HTML elements from the body of an HTML document using AJAX before transmitting it as data to the controller

My JSP page contains two buttons labeled "download" and "sendemail". When the "Sendmail" button is clicked, an ajax method is triggered to generate a PDF version of the HTML body and send it to the back-end controller. I attempted to utilize the following ...

Receiving an error response from the server upon subscribing to an Angular service (2/4/5/6)

I'm currently facing an issue with verifying my OTP. Depending on the response received from the server (whether it's due to OTP mismatch or OTP expiration), I need to display the appropriate error message. However, I am struggling to figure out ...

Is there a way to achieve the same zooming and panning effects on an element using CSS transform instead of jQuery's

If you click on the following link, you will see a jsFiddle that I have created to demonstrate my question: http://jsfiddle.net/VbCcA/3/ In my project, I have developed a function that allows for panning and zooming to a specific element. This function i ...

Tabs on Ionic Page

I have a mobile app built with Ionic 3 and Angular that I am currently in the process of upgrading to Ionic 6. The app does not use tabs throughout, but certain pages within the app have tab functionalities. Here is a simplified example: foo.html: <io ...

Hiding the header on a specific route in Angular 6

Attempting to hide the header for only one specific route Imagine having three different routes: route1, route2, and route3. In this scenario, there is a component named app-header. The goal is to make sure that the app-header component is hidden when t ...

"An error has occurred in the file system, make sure to handle it when

I am encountering an issue with submitting a form using jQuery's ajaxSubmit() function. The problem arises when the file selected in the form is renamed, deleted, or made inaccessible before submission, leading to potential discrepancies in whether th ...

What is the best method for updating a webpage's content simultaneously using ajax?

For instance: In a browser, there are two tabs open displaying the same page. However, an issue arises when updating the content of the first tab using ajax because the changes only appear in the second tab after reloading the page. Is there a way to ensu ...

What is the best way to invoke a function only once in typescript?

Struggling to implement TypeScript in React Native for fetching an API on screen load? I've been facing a tough time with it, especially when trying to call the function only once without using timeouts. Here's my current approach, but it's ...

Error: Parsing error - Unrecognized character "@" in Angular module

Currently I am delving into the realm of webpack and attempting to integrate it into my project. However, I seem to have hit a roadblock as I encounter the following error. Despite my efforts to troubleshoot and research, I cannot seem to find a loader spe ...

Steps for integrating Stanford's NLP into a web application

I have successfully developed a project utilizing Stanford's NLP API and models. Now, I am looking to integrate this Java-based project onto the web. After seeing the demo provided by Stanford-NLP, I am curious about the process they use to achieve th ...

Embed a JavaScript widget into an Angular template

I have a new widget that I want to integrate into my Angular view. The code provided by the widget's hosting site is as follows: <script src="http://www.somesite.com/widgetfile.js"></script> When tested on a standard HTML site, the widge ...

Tips for updating span content within an automatically generated table in Django by leveraging AJAX feedback

On my Django website, I have a products page where I can add items to the cart by clicking an "Add to Cart" button. These items are added as order items based on the item's primary key. Now, on the Cart page, I can see the specific products that have ...

Tips for maintaining license comments in TypeScript 2.5

When creating JavaScript libraries using TypeScript v2.5 and tsc, it is important to include license comments in the built files. However, the removeComments configuration in the tsconfig.json file can remove certain comments, including license comments. ...

Getting a variable from an ajax call and using it in a Pug template

Currently, I am experimenting with Express and Pug to learn some new concepts. Upon making a request to a website, I received some dynamic information stored in an array. However, I am facing challenges when trying to iterate over this array using Pug. The ...

What is the solution to fixing the error message "Cannot redeclare block-scoped variable 'ngDevMode' "?

I encountered this error: ERROR in node_modules/@angular/core/src/render3/ng_dev_mode.d.ts(9,11): error TS2451: Cannot redeclare block-scoped variable 'ngDevMode'. src/node_modules/@angular/core/src/render3/ng_dev_mode.d.ts(9,11): error TS2451 ...