There seems to be an issue with the angular service failing to

I am a beginner in Angular and working on my first web project where I am implementing a service for the first time. However, I am facing a problem:

var app = angular.module("mdmapp", ['ui.router']);

app.config(function ($stateProvider) {

    $stateProvider
        .state('creafund', {
            url: '/creafund',
            templateUrl: '/mdm/html/fundtype.html'
        })
        .state('creareceipt', {
            url: '/creareceipt',
            templateUrl: '/mdm/html/receipttype.html'
        })
        .state('fundentry', {
            url: '/fundentry',
            templateUrl: '/mdm/html/fundentry.html'
        })
        .state('payentry', {
            url: '/payentry',
            templateUrl: '/mdm/html/payentry.html'
        })
        .state('reports', {
            url: '/reports',
            templateUrl: '/mdm/html/reports.html'
        });

});


app.service('DataServer', function ($rootScope, $http) {

    //this function is to get the list of fund types.
    this.GetFundType = function () {
        $http.get('/mdm/server/app.php/GetFundType')
            .then(function (response) {
                return response;
            });
    };
});

//controllers for the various pages and sections.

app.controller('mainctrl', function ($scope, DataServer) {
    $scope.FundTypeList = DataServer.GetFundType();
});

app.controller('ftctrl', function ($scope, $http, DataServer) {

    $scope.SaveFundType = function () {
        var data = {desc: $scope.ftdesc};
        $http.post('/mdm/server/app.php/FundTypeCreate', data).success(
            function (data, status, headers) {
                $scope.ftdesc = null;
                $scope.FundTypeList = DataServer.GetFundType();
            }
        );
    };
});

In the above code snippet, I am encountering difficulty in fetching data from the 'datasever' service which fetches JSON responses from a REST API and will render a table.

Answer №1

To properly handle the promise in the controller, you should follow this approach:

function Service($http) {
    var service = {
      GetFundType: GetFundType
    };
    
    return service;

    function GetFundType() {
        return $http.get('/mdm/server/app.php/GetFundType');
    }
}

function ControllerA($scope,Service) {
  Service.GetFundType().then(function(result) {
    $scope.FundTypeList = result.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

React re-rendering only when arrays are filtered, and not when new elements are added

I need help with a table simulation where I can add and remove products. The issue I'm facing is that the component only updates when an item is removed, not when a new row is added. Currently, I am utilizing the useState hook. Below is my array data ...

Regular Expression: do not include comments that are placed inside quotation marks

Using the regular expression /#(.*?)\r?\n|#(.*?)$/g, I was able to parse the following content. However, it also matches the comment within the quotes. How can I prevent this from happening? # # this is a comment # but this is '# not a c ...

Setting a class based on the current route name or controller can be achieved by utilizing dynamic

Looking to assign a class depending on the current controller or current route (URL Segment 1). for example <body class="{{controllerName}}"> This approach allows for easier targeting of individual pages for CSS specificity if needed. ...

Developing unique custom methods in Django REST API for generic views

As an intern, I am currently working on a project that involves developing a DRF API to interact with a mobile app built by my colleague using the Ionic framework. Our task is to create new users, and here is the method in my view: class NewUser(generics. ...

Encountered a 404 error while attempting to access a specified route

I've encountered a perplexing issue where I'm receiving a 404 error specifically for a search route, despite other routes working perfectly. My goal is to search for a post using its title and/or tags as parameters. Let's take a look at the ...

Attempting to wrap my head around the implementation of callback functions in THREEJS

Below is a snippet of code taken from a THREE.JS example that functions properly. I have used this code to create my own art gallery by reverse engineering it from the three.js code. However, I am puzzled by how materialPainting1 can be utilized in the cal ...

The compiler mistakenly infers an incorrect type while utilizing a default value for a discriminated union type

I am currently working on a simplified component: export type BaseProps = { size?: 'xs' | 'sm' | 'md' | 'lg'; } type ButtonAsButtonProps = Omit<React.ComponentPropsWithoutRef<'button'>, ' ...

The screen-responsive navigation bar is experiencing functionality issues

I am facing an issue with my navigation bar on both desktop and mobile. When I maximize the window while the mobile navbar is open, it disappears as expected but the desktop navbar does not appear. I am using a bootstrap template and I am unsure if solving ...

Steps to remove information from a database using PHP, AJAX, and vanilla JavaScript (without jQuery)

I am facing an issue with deleting data from my database. Whenever I click on the delete button, it deletes the first row instead of the intended row. Below is my PHP code: <?php $connect = mysqli_connect("localhost","root","","abu"); if($conne ...

Tips for transferring information from an express rendering to a Vue component?

When working with an express route, page.js router.post('/results', (req, res, next) => { output.terms = "hello" output.results = [{"text": "hello world"}, {"text": "hello sunshine"}] res.render("/myview",output) }) The cod ...

Using a button click to toggle the vue-ctk-date-time-picker in VueJS

Currently, I am utilizing the Vue component - https://github.com/chronotruck/vue-ctk-date-time-picker within my own component. However, I am encountering an issue where I would like to maintain the component's original functionality while having a but ...

Is it possible to bind to a service variable in a controller without using $scope and utilizing the

As I delve into the world of controllerAs syntax in AngularJS, I've encountered a snag when attempting to bind a service variable. The traditional approach using `$scope.$watch` or `$scope.$on` would require injecting `$scope`, which seems counterintu ...

Implementing validation for multiple email addresses in JavaScript: A step-by-step guide

Currently, I am utilizing Javascript to perform validation on my webpage. Specifically, I have successfully implemented email validation according to standard email format rules. However, I am now seeking assistance in enhancing the validation to allow for ...

When utilizing Vuetify's v-for directive, each list item will reveal its menu upon being clicked

How can I make each item in my Vuetify list open a menu individually on click, instead of opening all menus at once when any item is selected? <v-list-item-group> <RecycleScroller v-if="drive_stop_info.drive_stop_list.lengt ...

The form response values consistently show as undefined, attempting to send them to the backend with no success so far after trying two different approaches

I've tried approaching this issue in two different ways, but both times I end up with a value of "undefined" instead of the user input from the form. Just to give some context, I'm using material UI forms for this project. The first approach inv ...

How to manage access controls for the Admin Page in node.js

Hi everyone, I am facing an issue with my admin page access control on my application. I want to restrict access to all users except the one named John. In my app.js file, here is what I have: app.get('/admin', requireLogin, function(req, res){ ...

javascript batch insert new key values

Is there a more elegant way to set multiple keys of an array in JavaScript? The current code may not be aesthetically pleasing, but it seems to be the only solution that works. var listData = []; listData['today'] = []; listData['data1&a ...

How can we remove the undesired characters from a string?

I've created a JavaScript code that searches for YouTube links on my webpage and replaces them with iFrame to embed the videos. It works perfectly fine. However, sometimes the YouTube links have additional parameters at the end like &t=3s or & ...

Is it possible to determine the duration of a JQuery AJAX call's execution?

Is it possible to measure the duration of a $.getJSON method call using timing code in jQuery/JavaScript? Additionally, is there a method to determine the size of the response Content-Length, measured in kilobytes or megabytes? ...

Identifying the window closing event in a window that was opened using window.open

As I utilize the window.open method to create a popup window for conducting tests, I am curious about how I can detect when a user closes this specific popup window. My goal is to have an event trigger when the user closes the popup window, especially fo ...