Continue perusing the Angular JS HTTP request

I'm currently delving into the world of web systems, still a bit green when it comes to Angular JS.

The feature I'm tackling now requires a POST call using Angular. Implementing the POST call itself isn't too tricky in Angular. However, my challenge is to maintain communication with the socket while the call is being made.

The process I've set up intentionally takes quite some time, but I want the progress status to be displayed in my Angular application. Therefore, I aim to send data along with the status update that can be dynamically shown in the app.

What would be the most effective approach for this scenario? While exploring WebSocket demos for Angular, I came across the option of creating my own HTTP layer on top of WebSockets to facilitate sending POST requests...

Answer №1

When making HTTP requests using the $http service, the process happens in the background, allowing you to display any desired content while the request is being processed. To track the status of the request, it is important to determine how you wish to measure that progress.

The introduction of progress events on the $http object is expected in a future version of Angular (possibly 1.6). If dealing with delays caused by uploading large files, consider creating a separate service that utilizes a raw XMLHttpRequest object instead of relying on $http. Referencing an example from MDN documentation:

var oReq = new XMLHttpRequest();

oReq.addEventListener("progress", updateProgress);
oReq.addEventListener("load", transferComplete);
oReq.addEventListener("error", transferFailed);
oReq.addEventListener("abort", transferCanceled);

function updateProgress (oEvent) {
  if (oEvent.lengthComputable) {
    var percentComplete = oEvent.loaded / oEvent.total;
    // ...
  } else {
    // Progress information cannot be computed as total size is unknown
  }
}

In cases where the delay is on the server side, such as waiting for a lengthy database query to complete, simulating a progress bar based on the average query runtime or displaying an indeterminate bar may be necessary:

https://i.sstatic.net/28rbY.gif

If there is a method to monitor progress on the serverside, another request can be initiated while the initial one is in progress to obtain progress updates. It will likely involve sending some form of identifier (like a query ID or request ID) to link the two requests together.

Answer №2

RequestDataFromAPIServer()
   .then(function(response){
      //Status bar is now hidden, data has been received
    });

checkCurrentStatus()
 .then(function(status){
     if(status === "completed"){
        //No further action needed
     } else{
        checkCurrentStatus();
     }
  });

Answer №3

If you want to manipulate HTTP calls, using an interceptor is a handy solution. Interceptors allow you to intercept the call before it is sent and after it returns from the server.

$httpProvider.interceptors.push(['$q', '$location', 'localStorageService', function ($q, $location, localStorageService) {
        return {
            request: function (config) {
                // Implement custom logic here

                return config;
            },

            response: function (result) {
                return result;
            },

            responseError: function (rejection) {
                console.log('Request failed with', rejection.status, 'status');


                return $q.reject(rejection);
            }
        }
    }]);

Alternatively, you can explore https://github.com/McNull/angular-block-ui for more options.

Answer №4

To implement a specialized service using $HTTP for executing a POST request, you can follow the example below:

app.factory('customService', ['$http', function($http){
     var httpFunctions = {
         handleSuccess : function(response, status, headers, config) {
            return response;
         },
         handleError :  function(error, status, headers, config) {
            return error;
         }
      };

      executePostRequest: function(dataToSend){
         var result = $http.post(
               'http://45.435.214.65/',
                dataToSend
         );

         result.prototype = httpFunctions;
         return result;
      }
}

Answer №5

When it comes to web sockets, a friend recommended socket.io which I've found effective for integrating with Angular in various single page applications. Take a look at this resource for additional information.

Best of luck!

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

"Exploring the Method of Inheriting from a BaseComponent in Angular 2

I’ve been working on an Angular project and I’m looking to streamline the creation of components with shared functionality. For example, let’s say I have a TeacherIndexComponent: @Component({ selector: 'app-teacher-index', templateUrl: ...

What is the best way to trigger a function (or directive) specifically when a tab is chosen in AngularJS?

Just starting to learn angularjs and I've created a page with 2 tabs using directives. I'm using $http to fetch json data from my server. My issue is that I don't want to make a request to the server until the user decides to view the other ...

Lamenting the Perils of Losing AngularJS Rootscope Data upon Refresh

Currently, I am facing an issue in AngularJS 1.x. When I save a value in the $rootScope and pass to the next page or router, unfortunately, the $rootScope value gets lost upon refreshing the page (F5/Window Reload). I need a solution that doesn't inv ...

A guide on conducting comparisons within a render in React

Currently, I am placing a component inside another component and the setup is shown below: render() { return ( <MyComponent value={this.state.measurement.Value} unit="kg" /> ); } My objective is to m ...

Exploring the world of web scraping using NodeJS and cheerIO

Can anyone help me figure out why I can't retrieve the HTML content while web scraping with Node.js and Cheerio? When I use the .html() function, it's showing an error saying that it is not a function. Here is the code snippet where I'm try ...

Exploring the Concept of Sending Data via AJAX Request

Trying to comprehend the intricacies of the HTTP POST request transmitted through jQuery's .ajax() or .post() functions. I'm puzzled by the presence of a 'datatype' parameter for server-sent data. What exactly will be included in the r ...

Issues arise with loading AngularJS directive properly within the context of service utilization

Currently, I am diving into the world of JavaScript and tackling a project that involves fetching data from MongoDB. My task is to write code in AngularJS to create a pie chart using Highcharts. Surprisingly, everything works smoothly when I solely use an ...

tips for revealing content in a div by sliding from right to left

I came across a fiddle that animates from bottom to top when the cursor hovers over it. Is there a way to modify it so that it animates from right to left on click, and then hides the content? After hiding the content, I would like to have a button that a ...

AngularJS 1: Dynamically updating input values in real-time

Hey everyone, I'm experimenting with Angular and have encountered a roadblock. I am trying to assign values to an input element using ng-repeat for a list of parameters. <input type="text" ng-model="parameters.inParameterName" class="form-control ...

JavaScript regular expressions only recognize certain characters

When submitting a form, I need to validate a field and ensure that only specific characters are allowed. The permitted characters include: a-z A-Z 0-9 % . " ' & - @ # $ * / + = [ ] ! I attempted to use the following regex for validation: var r ...

The function JSON.parse appears to be malfunctioning within the code, yet it operates smoothly when executed in

I am facing an issue with my Angular $http post service that communicates with a WCF service. The success handler in the http post is as follows: .success(function (data) { var response = JSON.parse(data); var tsValid = response.Outcome; defer ...

The error message "props.text is undefined in React Native" indicates that there is an issue with accessing the property text within

//**// import { StatusBar } from 'expo-status-bar'; import {StyleSheet, Text, View, Button, TextInput, ScrollView, FlatList} from 'react-native'; import {useState} from "react"; import GoalItem from "./components/GoalItem"; export defau ...

What is the best way to center a heading element within a section on a webpage?

I need assistance aligning the h1 element with the specific class wish to the center of its section, both horizontally and vertically. Unfortunately, I have been unable to achieve this thus far. Any guidance would be greatly appreciated. Below you will fi ...

c# server-side method is failing to execute when called from an AJAX request in ASP.NET

I am attempting to utilize ajax to call a C# method in the following manner. <a href="#divrecentQ" id="linkdivrecentQ" onclick="lnkClick();" aria-controls="divrecentQ" role="tab" data-toggle="tab&qu ...

Can you define the type of binding value in AngularJS 1.5(6) using TypeScript?

I am looking to define the type of binding items so that I am able to utilize components similar to functions. For instance, consider a component: angular.module('app').component('navBar', new NavBar()); class NavBar{ public bin ...

Divide a string within a JSON object and output it as an array

I've encountered a challenge while working with data received from an API. My goal is to loop through this information and generate HTML elements based on it. The issue lies in the 'subjects' data, which arrives as a string but needs to be m ...

Linking dynamic data to ng-model of a checkbox within an ng-repeat loop

In my controller, there is an array of objects structured like this: this.set = [{ "display": "Name", "pass": "name" }, { "display": "Subject", "pass": "subject" }, { "display": "Batch", "pass": "batch" }]; Checkboxes for name, ba ...

Display a pop-up alert message when the session expires without the need to manually refresh the page

I have a query regarding the automatic display of an alert message. Even though I have set the time limit to 10 seconds, I still need to manually refresh the page for the alert message to appear. The alert message should notify the user that the session ...

What is the best way to remove every other second and third element from an array?

I am looking to remove every second and third element of an array in Javascript. The array I am working with is as follows: var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"]; My goal is to delete every second and ...

Is there a way to detect a specific button press in react-native-picker-select?

I am currently utilizing the react-native-picker-select library. My objective is to set ingrebool to false when options a, b, c, or d are selected and true when option e is chosen from the data called ingre. How can I achieve this? Here is my code snippet ...