Why is my AngularJS controller receiving 'undefined' data from my service request?

Question: I am facing an issue where my service is successfully retrieving the necessary data, but my controller is not able to access it. What could be causing this problem?

Service: Below is the code that my controller calls.

// search.service.js
(function () {
    'use strict';

    angular.
        module('trips').
        factory('SearchService', SearchService);

    SearchService.$inject = ['BoatList'];

    function SearchService(BoatList) {
        var service = {
            getBoatList: getBoatList
        };

        return service;

        //////////////////////

        function getBoatList() {
            BoatList.query()
                .$promise
                .then(function (data) {
                    console.log(data);
                    return data;
                })
                .catch(function (error) {
                    return error;
                })
        }
    }
})();

Console Information:

I am confused because despite the service logging Array[7] containing the required data to the console during the API call's .then(), I am unable to access it in the controller. When debugging, I receive 'undefined'.

Controller: While executing the same code present in the service's getBoatList, everything functions correctly. However, when trying to retrieve the return data from activate(), I only receive 'undefined'.

//search.controller.js
(function () {
    'use strict';

    angular.
        module('trips').
        controller('SearchController', SearchController);

    SearchController.$inject = ['$stateParams', 'SearchService'];

    function SearchController($stateParams, SearchService) {
        var vm = this;

        vm.boatList = null;

        activate();

        ////////////////////

        function activate() {
            vm.boatList = SearchService.getBoatList();
        }
    }
})();

Recap: Even though the service is fetching and displaying the correct data on the console, the controller is unable to access the same information. How can I resolve this issue, and what misconception might be leading to this problem?

Answer №1

Your factory method needs to be updated in order to return a promise. The getBoatList method should now return a promise.

Revise your factory method as follows:

function getBoatList() {
   return BoatList.query().$promise;
}

In the controller, make sure to update the activate method like so:

function activate() {
   SearchService.getBoatList()
      .then(function (data) {
         vm.boatList = data;
      })
      .catch(function (error) {
         // handle errors here
      });
}

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

Error: The function props.addToCart is not accessible

While attempting to trigger my action on the client's click of the "addToCart" button to add a new product to the cart, I encountered the error message: "TypeError: props.addToCart is not a function." I am relatively new to Redux and have grasped the ...

Detecting collisions on a tile map using only JavaScript

Currently, I am developing a tile-based game using a traditional method (utilizing two for loops) and struggling with writing collision detection. I want the blue square to remain on the screen and appear on top of the tiles once the start button is clicke ...

Error: The reduce function cannot be applied to $scope.array as it is not a

I am currently facing an issue with a section of my code that involves loading attributes related to a page using drop-down lists. These attributes, namely instruments, style, and scoring, are fetched through a service call. For instance, when retrieving ...

Transform a JavaScript Array into a JSON entity

Currently working on a Mail Merge project using Google Apps Script, I've encountered an issue with displaying inline images in the email body. After sending the email using GmailApp.sendEmail(), all inline images are shown as attachments instead of be ...

Edge Browser does not support PHP Websocket technology

I created a multiplayer card game and incorporated a websocket for functionality. To integrate the websocket in php, I utilized this specific library After deploying it on my Ubuntu server, the program functioned smoothly on Chrome and Firefox (The fronte ...

After clicking the create button in AngularJS, the ngModel values become empty

My form has been simplified by using ngRepeat to create the input fields. The attributes for each item are defined in my controller. Below is the code for the ModalCtrl: ... $scope.form = [ { label: 'First Name', fieldType: 't ...

Struggling to create a <td> with AngularJS directive

I am currently working on creating a directive for a large set of repeated HTML code that involves using tables and table data cells. Although I have experience creating directives for div elements in the past, this is my first attempt at incorporating the ...

Stacking items when clicked on with jQuery UI Draggable

Can a draggable's stack procedure be activated by clicking instead of just dragging? I came across this solution, which essentially replicates the library code (with an important addition I included below). Is there a more elegant approach to achieve ...

Framer Motion does not support animations for exiting elements

Why is it that when I specify the exit property of framer motion to my HTML elements, they fail to animate upon being removed from the DOM? Here's an example of what my code looks like: <motion.div initial={{opacity: 0, y: -500}} animate={ ...

Executing the event handler only once

In my React project, I have a button that toggles a boolean state. However, I realized that the button can both set and unset the state due to its toggle functionality. I only want the state to be changed once. Is there a different function I can use ins ...

Discovering the country associated with a country code using ngx-intl-tel-input

In my application, I am trying to implement a phone number field using this StackBlitz link. However, I have observed that it is not possible to search for a country by typing the country code (e.g., +231) in the country search dropdown. When I type a coun ...

The post method in Express.js is having difficulty parsing encoded data accurately

I'm currently working on an AngularJS code that sends a POST request like this: var req = { method: 'POST', url: 'http://localhost:3300/addInventoryItem', headers: { 'Content-Type': 'application/x-www-form- ...

Tips for displaying Japanese characters followed by numbers in a single line on a web browser using CSS

Combining Japanese characters with numbers without spacing can present formatting challenges. For example, with a string like "新しいフォルダ000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 ...

Excel sheet upload button in Angular not functioning as expected

My project utilizes the Angular file upload component, which can be found at https://github.com/danialfarid/angular-file-upload Previously, everything was functioning correctly. However, after some refactoring, I seem to have inadvertently caused a breaka ...

Issue with setting innerHTML of element in AngularJS app upon ng-click event

Look at this block of HTML: <div class="custom-select"> <div class="custom-select-placeholder"> <span id="placeholder-pages">Display all items</span> </div> <ul class="custom-select- ...

Switch the dropdown selection depending on the checkbox status

I'm currently facing a bit of confusion with my project. I am constrained by an existing framework and need to come up with a workaround. To simplify, I am tasked with populating a dropdown list based on the selected checkboxes. I have managed to get ...

Tips for eliminating default classes from Mui Typography styling

I’ve been working on creating a Typography element and noticed some default MUI CSS classes added when debugging in the browser. I attempted to disable them by using empty arrays at the end of the sx prop, but it did not work as expected. In the image p ...

Once the ajax request is finished, load only the <script> tags that have specific ids

I'm currently implementing infinite-scroll to dynamically load more content which includes <script> tags that need to be executed. To achieve this, I have created the following code as an ajax-callback: JS on load ajax callback: function a ...

How can I designate a default value for a variable within a prop in a Vue.Js component?

I have a question regarding setting a default value for a prop using a getter. props: { userID: { type: String, default: '' } } The default value I want to set is obtained through: computed: { ...mapGetters('Auth&a ...

Using jQuery to target a specific item from a retrieved list of elements

I'm currently working on a photo gallery feature that is reminiscent of Instagram or Facebook user photos. My goal is to enable users to view details about each image (such as the date) in a box that appears over the image when they hover over it. E ...