Unable to transfer object from Angular service to controller

I am currently utilizing a service to make a $http.get request for my object and then transfer it to my controller.

Although the custom service (getService) successfully retrieves the data object and saves it in the responseObj.Announcement variable when I check the scope using Chrome's F12 developer tools, I am having difficulty passing that object to my controller.

  • Could there be an issue with one of the methods in either the service or the controller?

I have scoured StackOverflow for similar scenarios but haven't been able to find a solution yet.

getService


    class getService {
         static $inject = ["$http", "$window"]
         baseUrl: string = ConfigB.BaseAPIUrl;

         urlObject = {
             Announcement:  "Announcement",
         };

         responseObj = {
             Announcement :[],
         };

         constructor(
             public $http: any,
             private $window: any
         ) { }

         // method using generic promise object for announcements controller
         public getAnnouncements() {
             this.getRequest(this.baseUrl + this.urlObject.Announcement, "Announcement");
         }

         public passData() { 
             return this.responseObj.Announcement;
         }

         //Generic Angular $http promise object
         private getRequest(url: string, responseType:string) {

             this.$http.get(url)
                 .then((response) => {
                     this.responseObj[responseType] = response.data;
                 },
                 function (data) {
                     this.$window.alert("Error: " + data);
                 });   
         }
    }
    angular.module('App').service("getService", getService); 

    
<strong>My Controller:</strong>

class announcementController {
    static $inject = ["$rootScope", "$scope", "$window", "getService" ];

    Announcement: any = [
        { Message: "test" }
    ];
    
    constructor(
        public $rootScope: any,
        public $scope: any,
        private $window: any,
        private getService: any
    ) {}

    public getAnnouncements() {
        this.getService.getAnnouncements();
    }

    public setAnnouncements() {
        this.Announcement = this.getService.passData();
    }

    init() {
        this.getAnnouncements();
        this.setAnnouncements();
    }       
}
angular.module('App').controller("announcementController", announcementController);

Answer №1

To ensure that the setAnnouncements() function is only executed after the $http promise has resolved, it is important to pass on the promise returned by $http in your service and then retrieve the data in the controller once the promise is fulfilled.

Service code snippet:

public fetchAnnouncements()
{
    return this.sendRequest(this.baseUrl + this.urlObject.Announcement, "Announcement");
}

private sendRequest(url: string, responseType:string)
{
    return this.$http.get(url)
    ...

Controller code snippet:

public getAnnouncements() {
    return this.myService.fetchAnnouncements();
}

initialize() {
    this.getAnnouncements().then(() => {
        this.setAnnouncements();
    });
}

Check out an example on JSBin

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

Looping in REACT with state updates can cause the values to be overwritten

I'm encountering a problem with my function in React that updates the state. It fetches data from a URL in an array and creates a new item, but when trying to update another state array with this new object, it keeps overriding the first item each tim ...

Failure to trigger an event in Vue.js

I've implemented an overlay feature for my modal that should toggle the modal when clicked. Here's the code snippet I have in my mounted() method: const overlay = document.querySelector(".modal-overlay"); overlay.addEventListener("click", this ...

Easily visualize the JSON object hierarchy within Eclipse using JavaScript

Is there a way to view the JSON parse objects structure in Eclipse without using console.log() in Chrome due to cross domain issues? I need assistance with how to view the [object Object] returned structure from Json.Parse. ...

Is a Javascript-only application compatible with Amazon S3 cloud storage?

I am currently investigating the validity of the following statement: Based on my research, it seems unlikely to create a web application using only JavaScript - without any server-side logic - hosted on Amazon S3 that can also store data solely on S3 whi ...

How can you set a checkbox to be selected when a page loads using Angular?

On page load, I need a checkbox to already be 'checked', with the option for the user to uncheck it if they want. Despite trying to add [checked]="true" as recommended in some Stack Overflow answers, this solution is not working for me. <label ...

The system encountered an issue while trying to access the 'bannable' property, as it was undefined

message.mentions.members.forEach(men => { let member = message.mentions.members.get(men) if (!member.bannable) return message.reply(not_bannable) const reason = args.slice(1).join(" "); member.ban({reason: reason ...

Issue with Ionic Capacitor React & Typescript build process for Firebase Functions

Recently, I've been working on a cutting-edge Ionic Capacitor React application that utilizes Typescript with a Firebase backend. While everything has been running smoothly so far, I encountered some challenges when trying to build Firebase Functions. ...

No data stored in Angular service array

I am facing an issue with storing JSON data in a shared array within a service. The problem arises when I try to update the array with new content, as it seems that clearing the array before loading new data doesn't work properly. Here is how my serv ...

Untangling REGEX URLs for Effective Filtering

I am currently working on creating a filter for a video list. I have successfully put together a string that includes all the values selected by the user for filtering. Right now, I am passing this string as a parameter through the URL. For example: NOTE ...

What could be the reason for the malfunction of my checkbox styling?

I have designed custom checkboxes and radio buttons with CSS styling as shown below: input[type="checkbox"]:checked + label:after, input[type="checkbox"][checked="checked"] + label:after, input[type="radio"][checked="checked"] + label:after, input[type="r ...

Change the class name using jQuery when scrolling

Currently utilizing bootstrap as my primary css framework. My goal is to dynamically toggle a class on the navbar once the user scrolls past the prominent header image located at the top of the website. UPDATE: Admitting I made an error and had a momenta ...

The chart is failing to update with the data it obtained through Jquery

Scenario: I want to populate a chart using data fetched by Jquery. $.getJSON("/dashboard/", function(data, status) { var test_data=data console.log(test_data) chart.data.datasets[0].data=test_data; ...

Utilizing SetInterval for dynamically changing the CSS background image URL

I'm starting to feel frustrated with this situation... I have a solution where the CSS background is coming from a webservice. Currently, the system refreshes the entire page using HTML: <meta http-equiv="refresh" content="300" /> ... body { ...

The callback function `(err: any, data: any) => void` does not share any properties with the type `RequestInit`

Inspired by the tutorial at , I am working on a time-based visualization. I am currently using version "d3": "^5.4.0". Here is the code snippet: d3.json('http://127.0.0.1:5000', function (err, data) { if (err) throw err; // Cre ...

Order of custom code and JQuery in ASP master page

Using an ASP master page to include all the Javascript and jQuery files has presented a challenge for me. Specifically, the jQuery function in OrderManagement.js $(".menu-item").click(function () { window.alert("some text"); }); fails to execute whe ...

Use jquery and json to automatically populate select fields based on specific threshold values when they are changed

Looking for guidance on using jQuery to dynamically populate four select fields based on a four-level JSON array for a webshop, depending on threshold values. I'm seeking help with dynamically changing the selects only if the given value is greater t ...

The setInterval function continues to execute endlessly even after each interval is three months

I need to remove all expired OTP records every three months. In the file /sheduled-tasks/OTPRecords.js const prisma = require("../services/prisma"); const THREE_MONTHS = 1000 * 60 * 60 * 24 * 90; async function deleteExpiredOTPRecords() { ...

Tips for enhancing contrast in MUI dark theme modals

Currently, I am implementing MUI dark mode for my Next.js application. While the MUI modal functions perfectly in light mode, I am struggling with visibility issues when using it in dark mode. The contrast is not strong enough, making it difficult to disti ...

Encounter a snag when attempting to upgrade to React version 16.10.2 while working with Ant Design Components - the error message reads: "

After upgrading to the latest React version 16.10.2, I encountered issues while using Ant Design Components. I specifically wanted to utilize the Title component from Typography. Here is an example of what I was trying to do: import { Typography } from & ...

What happens when a JavaScript variable is used inside the $.ajax function and returns null?

I've come across numerous questions that are similar to mine, but unfortunately, I haven't been able to find a solution! My issue involves attempting to open a PHP file while passing certain Javascript variables into the URL using $.ajax. However ...