Utilizing an AngularJS service to communicate with a web API

Having trouble retrieving data from a web api and passing it back to a JavaScript file. I've tried using http://localhost:8584/api/Testing/5 to see if there are any results, but no luck so far.

//This is the JavaScript controller that calls the service.js
app.controller('mainController', function ($scope, service) {
    
    returnData();
    function returnData() {
        var getData = service.get(5);

        //The data returned from the web api will be displayed with $scope.newmessage
        getData.then(function (pl) { $scope.newmessage = pl.data },
              function (errorPl) {
                  $log.error('failure loading Employee', errorPl);
              });
    }
}
            
//this is service.js
app.service('service', function ($http) {
    
    var baseUrl = 'http://localhost:8584/';
    this.get = function (Id) {
        return $http.get(baseUrl + 'api/Testing/' + Id);
    }
});


//This is my web API controller
namespace angulartestOne.Controllers
{
    public class TestingController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/<controller>/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/<controller>
        public void Post([FromBody]string value)
        {
        }

        // PUT api/<controller>/5
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/<controller>/5
        public void Delete(int id)
        {
        }
    }
}

Answer №1

To ensure the data is returned only when it's ready, a callback function from the service's get method should be implemented. Keep in mind that this process is asynchronous and data can only be retrieved when it becomes available.

Modify your service code as shown below:

app.service('service', function ($http) {
  var baseUrl = 'http://localhost:8584/';
  this.get = function (Id, callback) {
     $http.get(baseUrl + 'api/Testing/' + Id)
      .then(function (response) {
           callback(response.data);
      });
   }
 });

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

Avoiding Scroll Reset on Browser Navigation with Delayed Transition

I've recently implemented a delay in my router configuration on my website. However, I've noticed that when I try to navigate using the browser's back and forward buttons, it first jumps to the top of the page because of the delay set with { ...

jquery global variable not working as expected

I'm having trouble making some variables global outside the jQuery function. I've tried using 'var' to declare them first and then assigning values, but when I try to log() them at the end, I get undefined. var lat, lon; $.get('ip ...

Using AJAX to Send Requests to PHP

Embarking on my first ajax project, I believe I am close to resolving an issue but require some guidance. The webpage file below features an input field where users can enter their email address. Upon submission, the ajax doWork() function should trigger t ...

Discovering the method for retrieving JavaScript output in Selenium

Whenever I need to run JavaScript code, the following script has been proven to work effectively: from selenium import webdriver driver=webdriver.Firefox() driver.get("https:example.com") driver.execute_script('isLogin()') However, when I atte ...

Error encountered when attempting to create an index in ElasticSearch due to

I am encountering an issue with the elasticsearch npm module while attempting to create an Index, resulting in a TypeError with the following message: Unable to build a path with those params. Supply at least index The code snippet I am using is as follo ...

The form refuses to submit using ajax, although it typically submits without any issues

Check out this code snippet: $('.saveCheck').on('click',function() { var form = $(this).parents('form'); form.submit(function (event) { $.ajax ({ t ...

Removing JSON data with JavaScript

Currently, I am working on developing a custom discord bot for a server that I share with some friends. The bot includes a warn system and level system, and I have successfully implemented JavaScript to write data to an external JSON file. { "othe ...

Please optimize this method to decrease its Cognitive Complexity from 21 to the maximum allowed limit of 15. What are some strategies for refactoring and simplifying the

How can I simplify this code to reduce its complexity? Sonarqube is flagging the error---> Refactor this method to reduce its Cognitive Complexity from 21 to the allowed 15. this.deviceDetails = this.data && {...this.data.deviceInfo} || {}; if (th ...

Using yargs to pass parameters/arguments to a Node script through an npm script

Is it feasible to retrieve a key from yargs when utilizing as an npm script argument? A user inputs in the OSX terminal: npm run scaffold --name=blah which triggers in package.json: "scaffold" : "node ./scaffold/index.js -- " This leads to const yar ...

Solving the issue of overflowing in the animation on scroll library

I've recently started using a fantastic library called animation on scroll (aos) for my web development projects. This library offers stunning and visually appealing animations. However, I encountered an issue where it causes overflow problems in my H ...

The function User.find does not exist and it is not possible to replace the `users` model after it has

Currently, I am experimenting with using mongoose, mongoDB, next, and express in a test project. Despite referencing solutions like Cannot overwrite model once compiled Mongoose and others, I am encountering issues unique to my situation. Upon initializat ...

After installing babylonjs via npm, encountering the error 'Unable to utilize import statement outside a module'

Recently, I've been working on setting up babylonjs through npm. Starting with a new project, I ran npm init and then proceeded to install babylonjs using npm install babylonjs --save, following the provided documentation. I then created a JavaScript ...

Leverage the response data from the first AJAX call as a variable for the second

I have a script that performs two ajax calls - the second one is nested within the success handler of the first. However, I need to utilize the data retrieved in the first success handler as an additional variable to send in the second ajax call, and then ...

Having Trouble with $.ajax Function in my Program

After spending three days experimenting with various methods, I'm still unable to successfully use the Javascript ajax command to send form values to a php script. Despite no errors being displayed and the scripts running smoothly, nothing is getting ...

Add a border to the 'contenteditable' class in a Bootstrap table after it has been modified

Looking for help with JavaScript and jQuery! I have a script that creates an HTML table from a CSV file, using Bootstrap for styling. I want to add CSS or a border to a table cell after it has been edited, but my jQuery attempts haven't worked. Any su ...

The polygon array feature is not functioning as expected in the Google Maps API

I'm currently facing an issue with a code that is supposed to draw polygons from an array in the Google Maps API, but unfortunately, it doesn't seem to be working as expected. <!DOCTYPE html> <html> <head> <script src ...

Executing a Function Prior to onClick Event of a Link Element in Next.js

While working on a slider/carousel, I encountered an issue. Each photo in the slider should be draggable back and forth, with a click taking the user to a product page. I am using next.js with react-flickity-component for this purpose. Please note that thi ...

Guide to fetching and returning data from AJAX using a function

In my JavaScript file, I have a function that retrieves a value asynchronously from the server: function retrieveValue(userId) { $.ajax({ type: "POST", url: "http://localhost/bghitn/web/app_dev.php/get_number_of_articles", data ...

Applying a custom class to a particular row in an AngularJS datatable using the created

I am currently working with AngularJS datatables and I want to apply a custom class to a row if a specific condition is met. Here's what I have attempted so far: this.dtOptions = DTOptionsBuilder.newOptions() ... .withOption('createdRow', f ...

Typescript encountering onClick function error during the build process

My current challenge involves creating a submit function for a button in my application. However, when I attempt to build the project, I encounter a typing error that is perplexing me. Despite trying various methods, I am unable to decipher how to resolve ...