What is causing the variable to be undefined in my code?

I'm having trouble retrieving a Rest array and displaying it on my HTML page. The issue I am encountering is that in my factory, I can successfully fetch the array and display its contents, but in my controller, I always end up with an Undefined variable. Here is my Factory:

.factory('coursesService', function($resource) {
                var service = {};
                service.getAllCouses = function (){
                    var Courses = $resource("/myproject/rest/training/trainings");
                    var data = Courses.query().$promise.then(function(data)
                            {
                        service.data= data;
                        console.log("line 1: ", service.data[0].name);
                        console.log("line 1: ", service.data[0].creator);
                        console.log("line 2: ", data[1].name);
                        console.log("line 2: ", data[1].creator);
                        return service.data;
                            }); 
                }
                return service;
            })

And here is my controller:

.controller("CoursesController",
            function CoursesController($scope, coursesService) {
                var courses = {};
                courses = coursesService.getAllCouses();
                console.log("courses: ", courses);
            })

The output I am receiving looks like this:

courses:  undefined
line 1:  Angular
line 1:  Object {id: "1", username: "User1", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f6a6c7a6d2e5f78727e7673317c7072">[email protected]</a>",    password: "password", userProfile: Object}
line 2:  JavaScript
line 2:  Object {id: "1", username: "User1", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f481879186c5b49399959d98da979b99">[email protected]</a>", password: "password", userProfile: Object}

Why am I getting `courses: undefined`? Shouldn't it be displayed after the list that I'm showing in the factory?

Answer №1

The function getAllCouses in your code does not return any value, resulting in always getting back undefined when calling it. Although the callback within the query promise's then handler returns something, it is not the result of getAllCouses.

To fix this issue, you need to ensure that getAllCouses returns the promise itself and then utilize the output within a then handler associated with that promise. You cannot directly use its return value if the execution of Courses.query() is asynchronous (if it wasn't, why is it yielding a promise?).

A corrected version of the code would resemble the following:

.factory('coursesService', function($resource) {
    var service = {};
    service.getAllCouses = function (){
        var Courses = $resource("/myproject/rest/training/trainings");
        var data = Courses.query().$promise.then(function(data) {
            service.data= data;
            console.log("line 1: ", service.data[0].name);
            console.log("line 1: ", service.data[0].creator);
            console.log("line 2: ", data[1].name);
            console.log("line 2: ", data[1].creator);
            return service.data;
        }); 
        return data;        // <=== Ensure to return the promise (`data` may be confusing)
    };
    return service;
})

After making these changes, you should adjust your controller as follows:

.controller("CoursesController", function CoursesController($scope, coursesService) {
    coursesService.getAllCouses().then(function(courses) {   // <=== Implement promise usage
        console.log("courses: ", courses);                   // <===
    });                                                      // <===
})

Remember, I'm not proficient in Angular development.

Answer №2

Instead of returning a value, getAllCourses() simply assigns values to two local variables, Courses and data.

The logs related to the Courses.query promise are delayed because it only resolves after the web request is finished.

Answer №3

To resolve the issue, I made some updates to my service and controller as shown below:

.factory('coursesService', function($resource) {
        return $resource("/myproject/rest/training/trainings", {
            query : {
                method : "GET",
                isArray : true
            }
        });
    });

I included the line

isArray : true 

and then proceeded to update the controller like so:

.controller(
            "CoursesController",
            function UserController($scope, coursesService) {
                coursesService.query(function(data) {
                    console.info("data: ", data)
                    console.log("1st course: ", data[0].name)
                    $scope.Courses = data; 
                });

Answer №4

This is how I resolved the issue:

.factory('coursesService', function($resource) {
        return $resource("/myproject/rest/training/courses")
    })

Here is the corresponding controller code:

.controller("coursesController", function($scope, coursesService) {
        coursesService.query(function(data) {
            $scope.Courses = 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

Tips for identifying functions that return objects

I'm trying to figure out how to extract the type from the object returned by a specific function. The function returns an object with two keys: X and Y. In my getItem function, I only need the type of X. I don't want to use the interface Selecte ...

Utilize JavaScript or Jquery programming to restrict the entry of special characters from the numeric keypad

For the project I'm working on, I need to block users from entering specific characters in a text box: !@#$%^&*(). Can anyone advise me on how to accomplish this using JavaScript/jQuery? The application is built with ASP.NET. ...

Update the login button to display as logout in Angular 13

I want to display a simple list with two buttons, where one button is shown if I am logged in and the other if I am not. <div> <li class="nav-item"> <button *ngIf="token === ''" ...

Zoom in on a canvas-inserted image by clicking it, using a snippet of jQuery and HTML5

I'm currently working on a canvas image that allows zooming in and out after clicking the control button. The original size of the red ball is 128x128px. However, when zooming in too much, the image gets clipped by its own container. How can I resolv ...

Could you provide me with a demonstration of cross-domain functionality?

Similar Inquiry: Methods to bypass the same-origin policy Let's consider two domains for this example - "" and "". The first domain "" is generating data in JSON format as shown below: { "str_info": [ { "str_name": "Mark ...

Encountered an Unhandled Runtime Error in NextJs: Invalid Element Type

Attempting to build an Instagram clone following a YouTube tutorial from a year ago has led to various errors arising from nextjs14. I have managed to resolve all of them except for one particular issue: Error: Element type is invalid - expected a string ...

Issue encountered during testing does not appear in final compilation and prevents tests from executing

Embarking on my maiden voyage with Angular 5... Currently in the process of setting up a Jasmine test tutorial found at this link: https://angular.io/guide/testing. However, upon initiation, an error throws me off course: ERROR in src/app/pizzaplace.serv ...

What is the best way to incorporate both images and text in PHP code?

I'm currently working on creating a large image call-to-action (CTA) for my new WordPress website. I've set up a new field group with the type "group" in ACF, and added some functions in PHPStorm. However, none of my images, text, or links are ap ...

Could someone kindly provide a detailed explanation of this Javascript code, breaking it down step

I'm currently learning Javascript and stumbled upon this code snippet. However, I'm having trouble grasping its functionality. Can someone please break it down for me step by step? var ar1 = [1, 5, 6, 4, 3, 5, 100, -20]; function funDo(ar) { ...

A guide on transferring one response to another in Express using piping

Is there a way to send a REST request within an Express route handler and then either modify the response with custom logic or pass it through as-is to res? I'm considering manually transferring all elements of the REST response to res (such as heade ...

A guide on using JavaScript with Selenium to continuously refresh a page until a specific element disappears

When working with selenium in JavaScript, I have a challenge where I need to constantly refresh the page until a specific element disappears. The issue arises because selenium uses promises, and using a for loop creates multiple promises even when the cond ...

The CanJS model is unable to retrieve data from a .json file

Implementing MVC using AMD in canjs with requirejs has been my current focus. Here's a look at my domains.json file: [ "1":{"uid": "1","urls": "domain1.abc.com"}, "2":{"uid": "2","urls": "domain2.abc.com"}, "3":{"uid": "3","urls ...

Switch the style of a set of thumbnail images when clicked

I am working with a set of thumbnails where one has an "p7_current" class applied, giving it a border, while the rest have an "p7_inactive" class removing the border. My goal is to have the last clicked thumbnail in a group of 6 to have the "p7_current" c ...

The discord.js TypeScript is throwing an error stating that the 'index.ts' file is missing when trying to run 'ts-node index.ts'

I have been working on creating a discord bot using discord.js and TypeScript. However, when I attempt to start the bot by running 'ts-node index.ts', I encounter the following error: Error: Cannot find module 'node:events' Require stac ...

Adjust the node's location in Cytoscape.js

I recently switched from using Cola to fCose in Cytoscape.js for graphing multiple graphs with no connections. With Cola, I was able to manually set node positions by tweaking the layout options. However, with fCose, despite adjusting variables like quali ...

Ways to display the ChaptersButton in Videojs-Player

I'm trying to incorporate videojs (version 8.10.0) into my project and provide viewers with a way to select chapters within the video. According to the official documentation, it seems that simply including a track element linking to a VTT file within ...

When querying the model, the result may be undefined

I'm encountering an issue where I can't access the content of an array of documents in my model and it's returning undefined. Here is the model structure (Project.js): var mongoose = require('moongoose'); var Schema = mongo ...

"Enjoy seamless page transitions with SPA implemented using AngularJS, where navigation occurs without any

I recently developed a small SPA application using Angularjs and Bootstrap. I followed all the specifications provided by Angular's website and other resources online. In order to dynamically include other pages in the main page, I utilized ng-view. ...

How come jQuery each is failing to iterate through all JSON items from two functions simultaneously with $.when?

After checking with the Chrome Network inspector, it appears that the json returns from both ajax functions are downloading completely. However, there seems to be an issue with the jQuery each function as it is only going through the first three items of t ...

Breaking apart a pipe-separated text and sending it through a JavaScript function

CSS: <div class="pageEdit" value="Update|1234567|CLOTHES=5678~-9876543?|5678"> <a href="https://host:controller">Update</a> </div> Trying to retrieve the data within the div and pass it into a JavaScr ...