Retrieve JSON data using AngularJS

Can someone guide me on how to make a GET request to my API endpoint and handle the JSON response in my code?

Sample Controller.js Code:

 oknok.controller('listagemController', function ($scope, $http) {
    $scope.init = function () {
        $http.get("/api/veiculos")
            .then(function (data) {
                alert(data.toJSON());
            }).catch(function (error) {
                alert("Error retrieving data!");
            });
    }
});

Here is the response I receive from the API when using curl in the terminal:

curl http://localhost:8181/api/veiculos
{
  "_links" : {
    "self" : {
      "href" : "http://localhost:8181/api/veiculos"
    }
  },
  "_embedded" : {
    "veiculos" : [ {
      "nome" : "daniela",
      "tipo" : "tipo",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8181/api/veiculos/559d59b1ccf2ebb2fc97e70e"
        },
        "contatos" : {
          "href" : "http://localhost:8181/api/veiculos/559d59b1ccf2ebb2fc97e70e/contatos"
        },
        "clientes" : {
          "href" : "http://localhost:8181/api/veiculos/559d59b1ccf2ebb2fc97e70e/clientes"
        }
      }
    } ]
  },
  "page" : {
    "size" : 20,
    "totalElements" : 1,
    "totalPages" : 1,
    "number" : 0
  }
}

Answer №1

It appears that the data is being retrieved successfully, but there may be an exception when attempting to display it using an alert.

To resolve this issue, try using JSON.stringify(data) instead of data.toJSON()

$scope.init = function () {
    $http.get("/api/veiculos")
        .then(function (data) {
            alert(JSON.stringify(data));
        }).catch(function (error) {
            alert("Error retrieving data!");
        });
}

How can I extract "nome" and "tipo" from the veículo object?

// Access the _embedded property of the data object
var embedded = data._embedded;

// Retrieve the veiculos property from the embedded object
var veiculos = embedded.veiculos;

// Extract the nome & tipo values (since veiculos is an array, refer to the first index like veiculos[0])
var nome = veiculos[0].nome;
var tipo = veiculos[0].tipo;

Answer №2

Give this a shot:

oknok.controller('listagemController', function ($scope, $http) {
    $scope.init = function () {
        $http.get("/api/veiculos")
            .then(function (data) {
                alert(data.toJSON());
            }).catch(function (error) {
                alert("Error retrieving data!");
            });
    }
});

Make sure to utilize .then and .catch instead of .success and .error.

Answer №3

Using alert in that manner is not allowed, but console.log can be used as an alternative.

 oknok.controller('listagemController', function ($scope, $http) {
    $scope.init = function () {
        $http.get("/api/veiculos")
            .then(function (data) {
                console.log(data.toJSON());
            }).catch(function (error) {
                console.log("Error retrieving 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

Receiving Json data from ASP.NET CORE 2.1 using JsonResult

Code snippet for a ASP.NET Core 2.0 controller: [Produces("application/json")] [Route("api/[controller]")] [ApiController] public class GraficResourcesApiController : ControllerBase { private readonly ApplicationDbContext _context; public Gra ...

Issues occurring with setting the variable using the Google latlng API

I've tried searching for solutions on various forums, including stackoverflow, but haven't been able to make it work. The issue lies in this code snippet where the variable 'pos' is not being set: var geocoder= new google.maps.Geocoder ...

Mistakenly appearing at the top of the window instead of the bottom of the window

Utilizing Vue.js to fetch resources from a Laravel API periodically and paginate(), after retrieving the initial 10 instances, I aim to get the next 10. Here's how my method looks: scroll () { window.onscroll = () => { let bottomOf ...

"Is there a way to convert a collection of lists into JSON format while

Here is a collection of lists including names, scores, and other data: [['Edan Daniele', '12.61', '5.00', '9.22', '1.50', '60.39', '16.43', '21.60', '2.60', '35 ...

Tab buttons that switch between different sections with just a click

Forgive me if this seems like a simple coding issue, but I struggle with javascript and need some guidance... I have a setup where two buttons (blue and yellow) toggle between different content divs. On another part of the page, there are also two buttons ...

Executing Javascript within an iframe

Is there a way to include a script in an iframe? I came up with the following solution: doc = $frame[0].contentDocument || $frame[0].contentWindow.document; $body = $("body", doc); $head = $("head", doc); $js = $("<script type='text/javascript&a ...

Unreachable prevState when utilizing the useState hook

I am currently working on a component where I need to capture the previousState of an element. However, no matter what I try, it keeps returning the initial value. This suggests that there is some re-rendering happening, causing it to constantly default to ...

Tips for customizing bootstrap code for registration form to validate against duplicate emails?

The contact_me form utilizes default code to handle success or failure responses from the server. The code calls msend_form.php for communication with the database and always returns true. It allows checking for pre-existing email addresses in the database ...

Tips for resolving the "Unexpected reserved word" error during the installation of Laravel Jetstream

I have been following the steps outlined on to set up Laravel Jetstream. Upon running artisan jetstream:install, I selected Livewire support, API support, email verification, and PHPUnit support for installation. Next, I executed npm install as per the ...

Insert multiple text box values as a new entry in an SQL database

Currently, I am implementing a code snippet to incorporate additional text boxes within a form. The main purpose is to enable users to input multiple languages they are proficient in. <script> jQuery(function($) { var i = 0; ...

Continuous scroll notification within the fixed menu until reaching the bottom

I'm looking to achieve a scrolling notification message that stays fixed at the bottom of a top-fixed menu while the body content continues to scroll normally. Here's an example in this fiddle: HTML: <div class="menu-fixed">I am a fixed me ...

Tips on assigning html actions/variables to a flask submit button

I am facing an issue with my Flask app where the form submission process takes a while for the backend to process. In order to prevent users from refreshing or resubmitting, I want to display a loading gif during this time. The current HTML code for my fl ...

Does Next.js pre-render every page, or does it only pre-render the initial page?

As I dive into the world of nextjs, I'm coming across conflicting information. Some sources claim that nextjs only prerenders the first page, while others suggest that all pages are prerendered by default. This contradiction has left me confused about ...

How can I set the value of scope on a click event in Angular?

I'm having trouble creating a toggle feature in my angular project. I can't figure out why it's not functioning properly. My expectation is that when the a-tag is clicked, the lower div should display. <div> ...

Encountering a Laravel Nova issue where attempting to override a Vue component leads to a Vue warning: Error

Recently, I decided to incorporate a user guide into my nova using the following Vue Shepherd library. To make this work, I made some adjustments in the files within the nova directory. One of these changes involved renaming the file "webpack.mix.js.dist" ...

The submission form is being triggered immediately upon the page loading

I have a form on the landing page that sends parameters to Vuex actions. It functions correctly when I click the submit button and redirects me to the next page as expected. However, there seems to be a problem. Whenever I open or refresh the page, the par ...

Fetch a single random profile image from a Facebook user's list of friends using Javascript

I'm currently facing an issue with displaying a random profile picture of the user's friends on Facebook. I attempted to troubleshoot it myself but ended up crashing the login button and now it's not functioning properly. Can someone please ...

Is it possible to exclusively target a child div using JavaScript in CSS, without affecting the parent div?

I'm in the process of developing a calendar feature where users can select a specific "day" element to access a dropdown menu for time selection. The functionality is working fine, but I've encountered an issue. When a user selects a time from th ...

socket.io establishes several sockets for each connection

At times, when the server is experiencing some load, connecting to the page may result in multiple sockets being created. If there is significant lag, the connection may never be established while additional sockets are generated every second indefinitely. ...

Is there a way to efficiently display more than 10 data items at a time using the FlatList component in react-native?

Here is the data I am working with: singlePost?.Comments = [ 0: {id: 82, content: "Parent1", responseTo: null} 1: {id: 83, content: "Child1", responseTo: 82} 2: {id: 84, content: "Parent2", response ...