Utilize an asynchronous factory service within another asynchronous service for seamless integration

My task involves the following steps:

  • Initiating a query to an API for a large dataset of names, possibly through a service/factory, using $q (async)
  • Implementing another service (also async) that will filter elements from the above factory based on a specific string (search field). The goal is to reduce the number of values so they can be efficiently managed by my select box.

    • My controller needs to invoke the second service, retrieve these filtered values, and assign them to a $scope property for usage in the select box directive.

I believe that I should inject only the second service/factory (narrowed values) into my controller. The first factory (large dataset) should be injected as a dependency into the second service where the comparison takes place and the filtered result set is generated.

However, I am uncertain about how to store the data from the large dataset factory once it's injected. When I try to console.log it, it appears as a promise:

Object {then: function, catch: function, finally: function}

rather than returning the actual dataset.

The initial factory mentioned:

    .factory('MedicationDisplayNamesFactory', function MedicationDisplayNamesFactory($http, $q){

        return {
            getDisplayNames: function(){
                return $http({
                    method: 'GET',
                    url: 'http://rxnav.nlm.nih.gov/REST/spellingsuggestions?name=ambien',
                    headers: {
                        'Content-type': 'application/json'
                    }
                });
            }

        };

        return MedicationDisplayNamesFactory;

    })

The secondary factory:

    .factory('MedicationMatchingNamesFactory', 
                ['$http', '$q', '$timeout', 'MedicationDisplayNamesFactory', 
                    function MedicationMatchingNamesFactory($http, $q, $timeout, MedicationDisplayNamesFactory){

        return {
            getMatchingNames: function(){
                var foo = MedicationDisplayNamesFactory.getDisplayNames().then(
                            function(response){
                                var bar = response.data.suggestionGroup.suggestionList.suggestion;
                            }
                        );

                console.log(foo);

                return foo;

            }
        };   


        return MedicationMatchingNamesFactory;

    }])

In the controller, I need to call:

$scope.myData = MedicationMatchingNamesFactory.getMatchingNames();

Just like this example.

Answer №1

I have implemented a callback function to handle HTTP responses and passed it as a parameter to the getMatchingNames method:

<!doctype html>
<html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.js"></script>
    </head>
    <body ng-app="plunker">
        <div  ng-controller="MainCtrl">
            <ul>
                <li ng-repeat="name in myData">
                    {{name}}
                </li>
            </ul>
        </div>
        <script>
            var app = angular.module('plunker', []);
            app.controller('MainCtrl', ['$scope', 'MedicationMatchingNamesFactory', function($scope, MedicationMatchingNamesFactory) {
                var setMyData = function(myData) {
                    $scope.myData = myData;
                }
                
                MedicationMatchingNamesFactory.getMatchingNames(setMyData);
            }]).factory('MedicationDisplayNamesFactory', function MedicationDisplayNamesFactory($http, $q){

                return {
                    getDisplayNames: function(){
                        return $http({
                            method: 'GET',
                            url: 'http://rxnav.nlm.nih.gov/REST/spellingsuggestions?name=ambien',
                            headers: {
                                'Content-type': 'application/json'
                            }
                        });
                    }

                };

                return MedicationDisplayNamesFactory;

            }).factory('MedicationMatchingNamesFactory', 
                       ['$http', '$q', '$timeout', 'MedicationDisplayNamesFactory', 
                        function MedicationMatchingNamesFactory($http, $q, $timeout, MedicationDisplayNamesFactory){
                            return {
                                getMatchingNames: function(callback){
                                    MedicationDisplayNamesFactory.getDisplayNames().then(function(response){
                                        var data = response.data.suggestionGroup.suggestionList.suggestion;
                                        callback(data);
                                    });
                                }
                            };   
                        }]);
        </script>
    </body>
</html>

Answer №2

After simplifying the two factories, I decided to store one factory's resultset in memory using sessionStorage, while manipulating that value in the second factory.

I believe this solution could benefit others, so I'm sharing it here:

// Storing the large dataset in sessionStorage
sessionStorage.allNames = angular.toJson(allNames);

// Retrieving the saved dataset and assigning it to a variable
var allNames = angular.fromJson( sessionStorage.allNames );

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

Utilizing D3.js to filter nodes and links by making multiple selections from a checkbox

I am interested in enhancing my current forced directed graph by adding more flexibility. You can access the Jsfiddle here. Currently, there are radio buttons that control the opacity of nodes and links. There are 4 types of nodes: Agent, Customer, Pho ...

"Select2 dropdown fails to function properly upon returning to the page using the browser's

I've encountered an issue while working on a search page with Select2 dropdowns. Everything functions smoothly upon the initial page load, however, problems arise when a user performs a search, hits the browser back button, and then revisits the page. ...

Modify the filtered class of ng-repeat using the $index value from the controller

Here is my ng-repeat code: <div class="{{event.who_seen_it | newEvent}}" ng-repeat="event in eventList" ng-click="openEvet(event.title,$index)"> <h3 class="event-title">{{event.title}}</h3> </div> I am using the {{event.who_se ...

Sort objects based on a specific property that they possess

In my current setup, I have an array of objects structured as shown below: $scope.people = [{name: {last:"Doe", first:"John"}}, {name: {last:"Smith", first:"Joe"}}]; My goal is to implement a live filt ...

Why does async return an empty array the first time it is used?

I'm currently developing a JavaScript application using Node.js. I have been experimenting with the async/await function. After running the code snippet below, I noticed that the first time I send a GET request, I receive an empty array. However, if ...

Leveraging Javascript within MVC3, either on a master page or child page

I'm currently developing a web application utilizing MVC3 and I am curious about the best practices for incorporating JavaScript. Specifically, I am uncertain about whether to include JavaScript in the master page as well as in individual child pages. ...

Updating information on a website

My goal is to allow users to provide input text that will dynamically replace existing text on the webpage. For example, if there is a name displayed in an HTML element, I have created a form where the user can type their own name and submit it. Once sub ...

Remove the AngularUI Accordion when using ng-repeat

Currently, I'm working on integrating a delete function into my ng-repeating accordion component. The delete button appears as expected, and the function is properly set up. However, when the delete button is clicked, the page reloads abruptly and red ...

Error message encountered during compilation: TypeError - bot.dialog is not recognized as a function within the Object

Hey there, I've been dealing with this error for the past few days. The code snippet below is from Microsoft docs, but when I try to run npm start, I encounter the following error: TypeError: bot.dialog is not a function at Object.<anonymous&g ...

Tips for transferring PHP variable from a drop down menu

Hello, I am currently working on creating a dropdown menu using the <select> tag. My goal is to have it so that when someone clicks on one of the options in the dropdown, a new window opens. Additionally, I want the PHP variable from the main page to ...

Unrecognized OnClick Function in AJAX

As someone who is relatively new to AJAX, I am trying to work on a project that involves fetching data from a route and using AJAX to create a table. Within this table, each row has a button that, when clicked, should trigger a POST request to add some dat ...

Learn how to choose multiple rows in a table using a combination of ctrl+click and Shift+click commands within react js

I'm struggling with a problem and need some assistance. I'm trying to implement a feature where a user can highlight a table row by pressing ctrl + left click, and when they press shift + left click, it should highlight all the row data from one ...

Setting up VideoJS Flash backup

Due to Firefox's restriction on using an .mp4 file in the <video> tag, I am required to utilize the Flash fallback option on my VideoJS player. When it comes to Chrome, Safari, and IE, I can customize my VideoJS player via JavaScript to perform ...

Having trouble identifying whether a file is a picture or video based solely on its extension

My current challenge involves determining whether an uploaded file is a video or a photo. This distinction is crucial as it dictates whether the file should be sent to my telegram bot as a video or photo attachment. Despite having what seems like a logica ...

The argument for the e2e test is invalid because it must be a string value

Currently, I am conducting an end-to-end test for an Angular application using Protractor. However, I encountered an error while running the test for a specific feature file. The UI value that I am checking is - WORKSCOPES (2239) Below is the code snippe ...

Refreshing forms in Angular 2

I am attempting to retrieve values from forms using the submit event. However, I am encountering difficulty resetting those forms later on. I am using an id called "myForm" and an onclick function to try and achieve this. <form (Submit)="addMarker()" i ...

PHP file secured to only accept variables posted from HTML form

This is a basic HTML/AJAX/PHP script I have implemented. <form id="new_user" action="" method="post"> <div class="col-md-3 form-group"> <label for="username">Username</label> <input type="text" class="form-control" name ...

Opening a window in ExtJS when another window is already open

It seems like I'm having trouble opening a new window on top of another window that is already open in ExtJS 6. I have tried setting the model to true and bringToFront to true, but unfortunately, neither of them is working as expected. https://i.sstat ...

Is there a way to trigger a function for both a left and middle click at the same time?

Check out this code snippet: $('a').on('click', function(){ myfunc($(this)); }); function myfunc(el){ console.log('Either left or middle click clicked on the link'); } a{ cursor: pointer; } <script src="https://aj ...

Leveraging .intersect/.intersectsBox to handle object collisions in threeJS

Currently, I am developing a simple breakout/arkanoid game using threeJS. The game features a paddle and a bouncing ball on the screen. My main focus right now is to make the collision detection work correctly so that when the ball hits the paddle, it boun ...