Using $q.all function in a controller to fetch data from a service and receiving an

For a considerable amount of time, I have been facing some challenges with an API call. Even though the console.log in my service is returning the necessary data, the controller seems to receive an empty object. I suspect there might be an issue with how I am handling my promises, but despite thorough inspection, I cannot pinpoint the problem. Currently, I am utilizing $q.all() to concatenate multiple get requests.

Below is the code snippet for my controller function:

$scope.getData = function(input) {
    exampleService.getData(input)
        .then(function(data) {
            console.log(data);
            $scope.savedData = data;
        }, function(error) {
            alert(error); // displays an alert message with -1 upon encountering an error
        });
};

And here is the service function implementation:

this.getData = function(input) {
$q.all([
    $http.get(url1),
    $http.get(url2)
]).then(function(response) {
    console.log(response); // returns an array of objects that are required
    return response;
});
return $q.all();
};

While attempting to return $q.all().promises, an error appeared in the console stating:

cannot read property 'then' of undefined

Ultimately, my goal is to access a specific property within each nested object in the array. For instance:

var returnedPromise = [
     {dataIDontNeed: 1, {dataIwant}},
     {dataIDontNeed: 2, {dataIwant}},
     {dataIDontNeed: 3, {dataIwant}}
]

I am seeking guidance on retrieving the dataIwant object from the array of objects before sending back the promise. Any assistance provided would be greatly appreciated.

Answer №1

Instead of creating another empty copy of $q, simply return the original $q.all promise from the service.

return $q.all([ $http.get(url1), $http.get(url2) ]);

Implement this in the controller:

service.getData({}).then(...

If you need to modify the results, add another promise that resolves immediately to the all function. If the data needs to be formatted differently, remove the unwanted property like so:

return $q.all([ $http.get(url1), $http.get(url2) ]).
then(function(results){
    return results.map(function(each){
        delete each.dataIDontNeed;
        return each;
    });
    });

Handle it similarly in the controller.

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

Navigate to a different HTML file following a JavaScript function in Ionic and AngularJS with Cordova

I am currently creating an Android application in Cordova Tools for Visual Studio using Ionic and AngularJS. My goal is to redirect to another HTML page once my function has completed its execution, but I'm having trouble getting it to work correctly ...

I'm all set to launch my express js application! What are the major security concerns that I need to keep in

As a beginner in deploying express applications, I find myself lacking in knowledge about the essential security measures that need to be taken before launching a web application. Here are some key points regarding my website: 1) It is a simple website ...

Exploring ways to display featured posts within specific category sections

I have 2 featured posts in 1 div id, one with a big class and the other with a small class. I want the big featured div to display posts based on categories. The code for the big featured post is shown below: <div class="main_feat"> ...

Tips for testing Sequelize with Jasmine

In my database/index.ts file, I set up a Sequelize database using the code below: import { Sequelize } from 'sequelize'; const { DATABASE_DIALECT, DATABASE_HOST, DATABASE_PORT, DATABASE_USER_NAME, DATABASE_USER_PASSWORD, DATABASE_NAM ...

What is the reason behind the C# button_clicked function not triggering the Javascript function?

When the user clicks the button, I want to test the C# code side. The method in the C# function should call a JavaScript function to display an alert with the results of a C# public variable. However, it seems that nothing is being called at all. At the bo ...

Unable to Click on Selenium Element

When a link is clicked on a website, the URL remains unchanged but a popup appears on the screen containing elements that can only be accessed after running driver.switchTo().defaultContent(). To access these elements, I have used a javascript executor com ...

What is the most effective method for displaying a child modal within a map?

Project link: Check out my project here! I have two key files in my project - App.js and PageFive.js. In App.js, there is an array defined as follows: state = { boxes: [ { cbIndex: "cb1", name: "Bob" }, { cbI ...

Incorporate JavaScript to enable the transfer of text from one textarea to another upon clicking a button, while simultaneously clearing the original textarea

After working on the provided code, I have managed to create a functionality where text from one textarea is copied to another textarea when a button is clicked using JavaScript. <head> <script type="text/javascript"> function displayOut(){ ...

Currently working on integrating a countdown timer using the Document Object Model (DOM)

Is it possible to create a timer in the DOM without using any JavaScript? I currently have a JavaScript code for the timer, but I want to convert it to work directly with the DOM without needing to enable JS. Any assistance would be greatly appreciated! ...

Locate a user within an array in Angular 5 by inputting a specific character into a textarea before initiating the search

I'm currently facing a situation with my textarea component... <textarea [(ngModel)]="message" id="commentBox" placeholder="Add your comment here..."></textarea> Additionally, I have a user list that retrieves data from an external API l ...

javascript add items to a container

I created a looping animation that features dynamic words, but I'm struggling to append all the spans into the <div id"wordcloud"></div>. Any assistance with this would be greatly appreciated. var interval = 100; var width = 800; var he ...

Having trouble getting a jQuery variable to work as an argument in an onclick function for an HTML

success: function(jsonresponse) { data = JSON.stringify(jsonresponse); $.each(JSON.parse(data), function (index, item) { var Id=item.id; var JobId=item.JobId; var eachrow = "<tr>" + "<td>" + item.id + "</td>" ...

Incorrect Matching with Regular Expressions

I'm working on a regular expression to validate a URL. var url = "https://www,google.com"; var urlRegex = /(https|http)?:\/\/(?:\w[\-\w.]+)(?:\/[\-\w+&@#\/%=~_|!:,.;]*)?(?:\?[\-A-Z0-9+&@# ...

Displaying live data from a spreadsheet directly on a sidebar

My goal is to extract data from another sheet in the same spreadsheet and present it as a dropdown selection in the sidebar. The code.gs file contains a function called getVisualData() that successfully retrieves the desired list: function getVisualData() ...

Enhancing jQuery Rating Plugin

Currently, I am working on customizing the jQuery Bar Rating System Plugin. You can view an example of the plugin by visiting this link: . The rating system on my end will resemble Example D. Rather than having the plugin based on user input, my goal is to ...

Retrieve the user information from Auth0 within the NestJS application

I am currently working on implementing Auth0 authorization in NestJS, but I am unsure of how to retrieve the user's data within the callback URL handler. In a normal express function, this issue could be resolved using the following code. The passpor ...

Determine if an element is being hovered over using jQuery

How do I determine if the cursor is hovering over an element using jQuery or JS? I attempted to use $('#id').is(':hover'), but it doesn't seem to be functioning as expected. It's worth mentioning that I am calling this line ...

What is the proper method for utilizing colspan within the footerData of a jqGrid?

Are you looking to customize the footer of your jqgrid as shown in the example below? I am trying to set up a custom footer for my jqgrid similar to the one displayed above. I have already enabled the footerrow:true option and used $self.jqGrid("footerDat ...

What could be causing my sticky positioning to not function properly when I scroll outside of the designated

My website is organized into sections, with each section corresponding to a hyperlink in the navigation menu. I've applied the CSS property position: sticky to my navbar, which works as expected within the section bounds. However, I want my red navbar ...

React 18 doesn't trigger component re-rendering with redux

In my code, I have implemented a custom hook to handle global data fetching based on user authentication. Here is an example of the hook: const userState = useSelector(state => state.user.state) useEffect(() => { if(userState === "authentic ...