Obtaining information from an AngularJS Service Response and assigning it to the Controller Scope Object

I have a basic AngularJS 1.7 application where I am successfully fetching data from a web API using an AngularJS service. However, I am running into an issue where the data is not being populated in the controller scope object. I have verified that the data is being retrieved from the database via the Web API while debugging the AngularJS service. I am not sure what I am missing in order to resolve this issue.

Service.js

(function () {

    var app = angular.module('myApp');

    app.factory('websiteService', function ($http, $q) {
        var factory = [];
        var deferred = $q.defer();
        var baseURI = 'http://localhost:59029/api';

        factory.getAllStudents = function () {
            $http({
                method: 'GET',
                url: baseURI + '/Website/GetAllStudents'
            }).then(function (response) {
                deferred.resolve(response);
            }, function (error) {
                deferred.reject(error);
            });
            return deferred.promise;
        }

        return factory;
    });
})();

Controller.js

(function () {

    var app = angular.module('myApp');

    app.controller('websiteController', ['$scope', '$http', 'websiteService', '$filter',
        function ($scope, $http, websiteService, $filter) {
            $scope.TestWebsite = "TestWebsite";
            console.log($scope.TestWebsite);

            //GET Students
            websiteService.getAllStudents()
                .then(function (response) {
                    $scope.FetchedAllStudents = response;
                    // ISSUE: DATA NOT POPULATED HERE
                }, function (error) {
                    // error handling here
                });
        }
    ]);
})();

Answer №1

Instead of creating a promise with $q.defer, you can simply rely on the promise returned by the $http service:

app.factory('websiteService', function ($http, $q) {
    var factory = [];
    var baseURI = 'http://localhost:59029/api';

    factory.getAllStudents = function () {
        return $http({
            method: 'GET',
            url: baseURI + '/Website/GetAllStudents'
        }).then(function (response) {
            return response.data;
        });
    }
    return factory;
});

To learn more about this approach, check out Is this a "Deferred Antipattern"?

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

What could be causing the jQuery change function to stop working after loading HTML with AJAX?

When loading a form, I use AJAX to dynamically populate a select element from a PHP file. Previously, my change function was working fine (it displayed another input when 'other' was selected). However, after implementing the dynamic AJAX populat ...

Changing the name of a React Native sample application

I am currently working on a project based on this App example: https://github.com/aksonov/react-native-router-flux/tree/master/Example When I tried to change the following lines: index.ios.js import App from './App'; AppRegistry.regist ...

Is it possible to avoid passing each individual Vue prop by destructuring them?

Essentially, I am working with a component <Device> v-for="device in devices" :key="device.name" :device="device" :name="device.name" :number="device.number" :type="device.type" :status=&qu ...

The images in the React slick carousel appear to be slightly out of

I'm experiencing blurriness in my carousel when it animates with card items. Despite searching for a solution, I haven't found one yet. My tech stack includes Next.js and TypeScript. const ref = useRef<any>(); const settings = { arro ...

What is the best way to make my if statement pause until a GET request finishes (GUARD) with the help of Angular?

I am currently working on implementing admin routes for my Angular app, and I have used a role guard to handle this. The code snippet below showcases my implementation: However, I would like the get request to finish executing before the if statement begi ...

Saving the Chosen Option from Button Group into react-hook-form State

Struggling to save the chosen value from MUI Button Group into react-hook-form's state, but encountering challenges with the update not happening correctly. view codesandbox example Below is a simplified version of my code: import { ButtonGroup, But ...

Does the arrangement of props matter in JSX?

Assuming the o object has a key/value pair of: foo: 'bar', can I expect these results to hold true?: // foo will be 'bar' <MyComponent foo='should not override' {...o} /> // foo will be 'overridden' ...

React component allowing for the reuse of avatars

As a novice in React, I've encountered a challenge. My goal is to develop a simple reusable component using MUI. Specifically, I aim to create an avatar component that can be easily customized with different images when called upon. I want the flexibi ...

Utilizing props to transfer data between components in ReactJS

I have a React application where I am binding text values when a specific div is clicked. However, I am now faced with the challenge of passing these text values to another component using props. This is what my code looks like: class PostOptionBar exten ...

Is Nextjs the best choice for developing the frontend code exclusively?

When deciding whether to use Next.js or plain React for my front-end development, should I consider that a back-end already exists? If I am not planning to write a new back-end, which option would be better suited for the project? ...

Using Angular 2 and Ionic 2 to create a promise that returns an observable

In my current scenario, I am facing a challenge in an Ionic 2 application where I have to retrieve data from storage and then use it to make an HTTP request. The issue arises because the SqlStorage methods return promises while the http method returns obse ...

Utilizing $http (REST) to send information from a form

Struggling to leverage Angular for CRUD processes, especially encountering difficulties with POST requests to the server. This is my controller: angular.module('myModule').controller("ListingCtrl", function($scope, posts) { $scope.addProje ...

What does the HTML and JS code look like when using Next.Js?

Here's an illustration of the desired result: codepen.io/j0be/pen/jWGVvV How can I implement this HTML and JS in Next.js? I am looking to customize this code using TypeScript and SCSS in Next.js. However, I am unsure about how to convert the HTML an ...

Is it possible to track unsuccessful email deliveries using MailApp?

In my Google Script program, I incorporate MailApp in the following manner: MailApp.sendEmail(AddressStringGlobal,EMailSubjectProperLanguageGlobal,"",{htmlBody: EMailBody}); The issue arises when I encounter a bad email address in my data set, causing my ...

In Internet Explorer, the AngularJS multiple select box becomes unselectable when there is a change in the scope

Having an issue with multiple select boxes using AngularJS. Everything works fine in Chrome, but in IE, after changing the scope, I am unable to select anything - it freezes the UI. I have two multiple select boxes where you can select a set from one and ...

What could be causing my Link to malfunction in my about.js file?

I've encountered an issue where clicking the link in my app doesn't produce any result, and I'm unsure of the cause. Below is the content of my app.js file: import './App.css'; import {BrowserRouter as Router, Routes, Route} from ...

Accessing Values from a Map Returned by Spring in an Angular Controller

I'm completely new to using Angular and I need some help with retrieving a map value returned from Spring inside an Angular controller. Could someone please assist me with this? Below is the code snippet for reference: app.js // Service --------- ...

The utilization of $(this) proves to be ineffective

I've been working on getting a script to add events to a specific DIV within a class using pep.js: $( ".drag" ).pep({ start: function() { $(".drag").addClass('color'); $('.drag').next(".text").fadeIn("slow"); ...

The $scope.$apply function is causing an exception because a $scope.apply process is already underway

I am facing an issue while trying to update my view based on the changes made to my $scope variables. During the digest cycle, after modifying the variables, I call $scope.$apply(). However, I receive an exception saying that $scope.$apply is already in ...

Generating HTML table rows dynamically in Angular based on the number of items stored in a $scope variable

In my current project, I am utilizing Angular to dynamically populate data in an HTML table. Instead of manually coding each row for display, I am in need of a solution that allows me to programmatically define each HTML row. The Angular controller snippet ...