Angular is patiently waiting for the Ajax service function to finish executing

Seeking help on retrieving the result of an $http request from my controller.

Below is my service code :

.service('postService', function($http, apiUrl) {

    return {
        post: function(uri, params) {
            $http.post(apiUrl + uri, params).then(function(items) {                 
                    return items.data;
            });
        }
    };
})

And here is my controller implementation :

var fetchResult = postService.post('my_service_url', {id: 'test'});
fetchResult.then(function(result) {
       $scope.data = result;
       console.log(data);
});

Encountering an error message:

getData is undefined

Any recommendations on how to resolve this issue?

Answer ā„–1

To successfully complete the API call, make sure to return the $http.post

return {
    post: function(endpoint, data) {
        return $http.post(apiUrl + endpoint, data);
    }
};

Next, don't forget to set up the then function:

var response = postService.post('my_service_url', {id: 'test'});
response.then(function(result) {
       $scope.resultData = result;
       console.log(resultData);
});

Answer ā„–2

Give it a shot using the $q module in AngularJS:

https://angular.io/api/ng/service/$q

This is an example of how your service code could be structured:

.service('postDataService', function($http, $q, apiUrl) {

    return {
        post: function(endpoint, data) {
            var deferred = $q.defer();

            $http.post(apiUrl + endpoint, data).then(function(response) {                 
                    deferred.resolve(response.data);
            }, function() {
                // handle errors
                    deferred.reject();
            });

            return deferred.promise;
        }
    };
})

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

When using React, it's important to verify if the page has been refreshed before updating the local storage based on the GraphQL query. If the page

Currently, I am working on implementing a hit counter feature that increments each time a user clicks a button. The setup involves GatsbyJS with React and utilizes a lambda function to store the count in FaunaDB. Additionally, the client-side functionality ...

Send an API call for every item in a given list

There is a function that I am working with: updateCustomers = (input) => { //let urls = input; let urls = [{ name: "localhost:8081", url: "http://localhost:8081" }, { name: "localhost:8082", url: "http://localhost:8081" }, { ...

The JQuery parseFloat() function seems to be consistently returning "NAN" whenever it is used with the .text property

I am currently encountering an issue with parsing the text property of an input element identified by the id currency-converter. My goal is to convert this text into a floating-point value so that I can proceed with applying mathematical operations to conv ...

Extracting data from websites by manipulating the Document Object Model with the help of Javascript and Ajax

Currently, I am in search of data for educational purposes from a website. Specifically, the website focuses on statistics in web development. The challenge lies in the fact that this particular site uses Javascript/Ajax to constantly update numbers. I w ...

What is the process for obtaining the number of video views using the YouTube API?

I have a straightforward question: How can I retrieve the number of video views using the YouTube API? Although the task is simple, I need to perform this query on a large number of videos frequently. Is there a way to access their YouTube API in order to ...

How can I change the transparency of a CSS background color using JavaScript?

I have a question about CSS: .class1 { background: #fff } Now, I need to achieve the following: .class2 { background: rgba(255,0,0,0.5) }; Is there a way to use JavaScript only to change the background property of .class1 and give it an opacity of 0.5? ...

Utilizing db.system.js Function within the $where Clause

Here is an illustration of a basic function that I have saved: db.system.js.save({_id: "sum", value: function (x, y) { return x + y; }}); However, when attempting to call it within the $where clause, a Reference not exist error occurs. <?php $collec ...

Update data in Angular pagination when clicked on

I'm currently working on adding pagination functionality to a website built with Angular and Bootstrap. I have successfully displayed the data with the correct number of rows per page, and the pagination component is showing the right number of pages ...

What is the method for applying the action (hide) to every table cell that doesn't include a specific string in its ID?

I have a table with cells containing unique IDs such as "2012-01-01_841241" that include a date and a number. My goal is to filter the table to only display three specific numbers by sending a request and receiving those numbers. Is there a more efficien ...

Countdown component in Ant Design failing to display correct date

Iā€™m currently working on developing a specific date component using react in conjunction with antd. Below is the code snippet I am utilizing: import { Statistic, Col, Row } from 'antd'; const { Countdown } = Statistic; const deadline = Date.pa ...

Embedding links in v-bind:href

I inserted a dynamic link inside the <header></header> section using the method mentioned here: Vue JS and appending a variable to end of a URL Below are the relevant codes: <tr class="notice-row" v-for="(myCase, id) in case ...

Guidelines for securing login access where the "IsApproved" field must be true before authorization

During the account registration process, I initially set the default value to false for the field IsApproved. I need to create security rules that allow login only for users with IsApproved:true, and redirect those with IsApproved:false to the accessdenied ...

Issue: Connection Problem in React, Express, Axios

I've encountered an issue while attempting to host a website on an AWS EC2 instance using React, Express, and Axios. The specific problem I'm facing is the inability to make axios calls to the Express back-end that is running on the same instanc ...

The inner workings of v8's fast object storage method

After exploring the answer to whether v8 rehashes when an object grows, I am intrigued by how v8 manages to store "fast" objects. According to the response: Fast mode for property access is significantly faster, but it requires knowledge of the object&ap ...

Having difficulty loading the JSON configuration file with nconf

I'm currently attempting to utilize nconf for loading a configuration json file following the example provided at: https://www.npmjs.com/package/nconf My objective is to fetch the configuration values from the json file using nconf, however, I am enc ...

What are some methods for transferring the state variable's value from one component to another in React?

I have the following scenario in my code: there is a Form.js component that interacts with an API, stores the response in the walletAssets state variable, and now I want to create a separate Display.js component to present this data. How can I pass the v ...

Changes have been made to the Vue object, however, it does not trigger a re-render

Whenever I hit the right arrow key, it adjusts the object without re-rendering it : <div class="map"> <div class="map-page" tabindex="0" @keyup.arrow-keys="show" ref="mapPage"> <template v-for="mapRow in mapMatrix"> < ...

Navigating through props outside a class component in React

I'm struggling to grasp how I can access props that are defined outside of a React class component. In the code snippet below, all props are clearly outlined except for this.props.checkboxArray, which is currently throwing an error "cannot read prope ...

Fullcalendar JS will easily identify dates with events, allowing users to simply click on those dates to redirect to a specific URL

When looking at the official example, we can see that the events are displayed in a typical calendar format: https://fullcalendar.io/js/fullcalendar-3.5.0/demos/basic-views.html Each event is listed in the calendar, and clicking on an individual event wi ...

Swap a jQuery class with another if the class for ul li is currently active

I am currently developing a form builder and I would like to customize the appearance, specifically changing the color of the text. I want the text to be white when the class is set to active, and black when the class is not active. Is there a way to achi ...