Passing retrieved REST data from service file to AngularJS controller

Hey everyone, I'm new to angular js and running into an issue with sending data from my service file to the controller, which is then supposed to be displayed in my HTML. Could someone please provide some guidance on how to solve this problem? Thank you!

Here's my service file:

"use strict";

angular.module("fleetListModule").service("fleetsService",

 function ($http) {
             this.getTrucks = function () {
                 console.log("before calling webservice");
                 $http.get('http://localhost:8080/login/rest/truckservices/getTrucks?truckId')
                 .success(function (data){
                     var trucks = data;
                     console.log("after calling webservice my data is", trucks);
                     return trucks;
                 });

             };            
         });

And here's my controller:

"use strict";

angular.module("fleetListModule").controller("fleetListController",
    ['$scope', 'fleetsService',  
function ($scope, fleetsService) {

   var truckData = fleetsService.getTrucks();
   console.log("inside fleet service", truckData);
   $scope.trucks = truckData;        
    console.log("outside fleet service", truckData);
 }]);

This is how it looks in my HTML:

<div class="panel1 panel-primary">
    <div class="panel-heading" align="center">TRUCKS</div>
    <table class="table  table-condensed table-striped " >
        <thead class="truck-list-header">
            <tr class="truck-list-header">
                <th>Truck ID</th>
                <th>Status</th>
                <th>Dest.</th>
                <th>Alerts</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat="truck in trucks" ng-click="summaryData(truck)" class="truck-list-body">
                <td>
                    <div><i class="fa fa-truck truck-icon"></i>{{truck.truckId}}</div>
                </td>
                <td>
                <span class="label {{truck.label}}">{{truck.status}}</span>
                </td>
                <td>{{truck.destination}}</td>
                <td>
                    <div><i class="fa fa-exclamation-triangle alert-icon"></i>{{truck.alerts}}</div>
                </td>
            </tr>
        </tbody>
    </table>
</div>

Below is a snippet of the JSON data received from localhost 8080:

{"truckId":"111","status":"Running","destination":"Winnipeg","alerts":"Nothing"}

Answer №1

It seems that your service function does not return any value and the return statement within the success does not have any effect.

A simplified version of the service using then is recommended as success is now deprecated:

this.getTrucks = function() {
  console.log("before calling webservice");
  // Return the promise created by `$http`
  return $http.get('http://localhost:8080/login/rest/truckservices/getTrucks?truckId')
    .then(function(responsePromise) {
      var trucks = responsePromise.data;
      console.log("after calling webservice my data is", trucks);
      return trucks;
    });

};

In the controller:

 fleetsService.getTrucks().then(function(truckData) {
   // Assign data inside promise callback
   console.log("inside fleet service", truckData);
   $scope.trucks = truckData;

 });
 // Avoid running this line before the data has been returned from the server
 console.log("outside fleet service", $scope.trucks); // This will be undefined

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

Chosen item from the dropdown menu in Bootstrap

I am utilizing Bootstrap in combination with RAILS. My main objective is: create a dropdown list with Bootstrap styling show the selected item in <p>, <div>, or <span> The JavaScript code appears as follows: $(function(){ $(".drop ...

Why are imported modules unable to reach global variables in Node?

As I delve deeper into using ES6 and organizing my code across multiple files for better readability and version control, I've encountered an issue that has me puzzled. In one of my scenarios, I have a class defined in a separate file called class.js, ...

Is there a way I can implement lazy loading of results without having to overhaul my entire Laravel + jQuery application built in the Single Page Application style?

I recently created a web application using the Single Page Application concept, but without utilizing any modern technologies or frameworks. In this application, I have a jQuery page that makes dynamic requests to a localhost - a Laravel instance that comp ...

WARNING: Alert raised due to the discovery of two offspring sharing identical keys, `${item}-${index}`

I have been facing the issue of receiving an error message 'ERROR Warning: Encountered two children with the same key, ${item}-${index}' and I am not sure what is causing it. Can someone please guide me on how to resolve this problem? Any help w ...

Verify if the JSON attribute is empty

My input contains the following: { "headers": { ... }, "body": { "RequestInfo": { ... , "Identificator": null } } <filter regex="false" source="boolean($ctx:Identificator)"> - check if it exists (even when it's ...

Error: identifier token was not expected

I'm struggling to make an ajax request using DataTable.js, but I can't seem to connect the dots. let php_data = '<?php echo $_path."|".json_encode($LNG). "|".json_encode($array_uzers)."|".$month ."|".$year."|".$membre."|".$user ."|".$deb ...

pdfmake: Stabilized Vertical Column Dimensions

I'm working on a project where I need to add text to a column with a fixed height and width. So far, I've successfully implemented a fixed width, but I'm struggling with setting a fixed height for the column. Below is the code I've bee ...

Ajax divides the data received from a MySQL database

I have been working on an ajax call that looks like this: function myCall() { var request = $.ajax({ url: "ajax.php", type: "GET", dataType: "html" }); request.done(function(data) { $("image").attr(& ...

Issue related to React Routing: "The component [AuthProvider] is being used incorrectly. All child components within <Routes> must be either a <Route> or <React.Fragment>."

Dealing with React Routing has been a challenge for me. I've integrated authentication using Firebase and it seems like I need to wrap my routes with the <AuthProvider>. However, I keep encountering an error stating that it's not a part of ...

FireFox is causing issues with both ng-view and Angular functions, rendering them unusable

My AngularJS sample application is running smoothly in Google Chrome, but when I tried to test it in Firefox, I encountered issues with ng-view and other functions not working properly. This is the structure of my application: Index.html <!DOCTYPE ht ...

How can you dynamically assign an ng-class to a specific column within a jqxgrid using a controller?

I have including all the essential scripts for angular, bootstrap, and jqwidgets. My goal is to conceal a specific column in the jqgrid by using the hidden-lg class within the controller of the grid. $scope.gridWidth = "100%"; $scope.columns = [ ...

Explore the inner workings and file contents of a package using the NPM registry API, by accessing a detailed JSON response

Can the NPM registry API be utilized to access an endpoint like https://registry.npmjs.org/jquery And examine the Tarbells structure and internal files without the need to download the package, in a JSON response similar to: { files: { js: registr ...

"Encountering a Dojo error where the store is either null or not recognized

I encountered an issue with the function I have defined for the menu item "delete" when right-clicking on any folder in the tree hierarchy to delete a folder. Upon clicking, I received the error message "Store is null or not an object error in dojo" Can s ...

Display the content alongside the UI Bootstrap tabset tabs

Just starting out with bootstrap and looking to implement the vertical tabset for my project. Here's a basic outline of what I have in mind: <tabset vertical="true" type="tabs"> <tab heading="Vertical 1">Vertical content 1</tab> & ...

Transforming Unicode escape sequences into symbols and displaying them in a DOM element

Using the latest versions of Firefox and Chrome with jQuery 1.x edge. When an ajax request returns a single line of minified JSON text like this: { "fromSymbol": "\\u04b0", "toCurrency": "AUD", "toSymbol": "\\u0024", "convFact ...

Display class name in React only when the variable is set to true

import React from 'react'; import logo from './logo.svg'; import './App.css'; function App() { return ( <div className="App"> <h1 className={ isTrue ? 'primary' : ''}>{ fa ...

Pass information from an HTML input field to the backend using JavaScript

Currently, I am utilizing Bootstrap within my HTML to develop a search page that will allow users to input a SQL query. Once the user enters their SQL query, it will be sent to a backend system that will execute the query in a database. The backend code is ...

Unable to retrieve the child value using getJSON

I am currently retrieving data from an API that provides information in a specific format. Here is an example of the JSON data I receive: { "total":1, "launches":[ { "name":"Falcon 9 Full Thrust | BulgariaSat-1", "net":"June 23, 2017 1 ...

Is `send()` considered an anonymous function?

I am testing ajax on a local server, but encountering an issue where the console is showing that send() is being identified as an anonymous function and I am receiving a blank document. The console displays: XHR finished loading: GET "http://localhost/js ...

Issue with rendering HTML in React child component

Using React 16, I am facing an issue while trying to create a child component in my project. The inner HTML of the child component does not render, but the component tag can be viewed using the dev tools. The code for my child component is as follows: im ...