Pass the outcome back to the calling function

I've been struggling with this issue for a while. I am working with ion-autocomplete and trying to retrieve data using a factory.

The Factory I'm using is as follows:

myApp.factory('items', function($http){
   return {
      list: function(query,callback){
        $http.get('http://192.168.100.100/myApp/products/' + query).success(callback)
        }
        };
        });

To fetch the data, I use:

   items.list(function(items) {
      $scope.items = items;
    });

In the autocomplete demo, the request data looks like this:

  $scope.getTestItems = function (query) {
                    return {
                        items: [
                            {id: "1", name: query + "1", view: "view: " + query + "1"},
                            {id: "2", name: query + "2", view: "view: " + query + "2"},
                            {id: "3", name: query + "3", view: "view: " + query + "3"}]
                    };
                };

I thought this solution would work:

   $scope.getTestItems = items.list(query,function(items)
        {   
        console.log(items);
        return items;
        }
        )

However, it's clear that it's not working. I also tried:

   $scope.getTestItems = function(query)
   {
   items.list(query,function(items)
        {   
        console.log(items);
        return items;
        }
        )
    }

Although this does show me the result in the console, it's not being returned to getTestItems.

Answer №1

Based on the documentation (assuming I have the correct library), it is possible to return a promise.

myApp.factory('items', function($http){
    return {
        list: function(query) {
            return $http.get(... + query).then(function(res) {
                return res.data; // extract the response data
                // refer to the "Returns" section at https://docs.angularjs.org/api/ng/service/$http#usage
            });
        }
    };
});

and in the controller:

$scope.getTestItems = function(query) {
    return items.list(query);
};

Answer №2

How about giving this a try?

Manufacturing Plant

 collection: function(query,callback){
    return $http.get('http://192.168.100.100/myApp/products/' + query)
 }

This technique involves returning the promise directly from the manufacturing plant.

Supervisor

$scope.fetchItems = function(query){
  items.collection(query).then(function(items){   
    console.log(items);
  });
}

The function will be triggered as soon as the promise is fulfilled.

Answer №3

One potential solution to consider is as follows:

myApp.service('products', function($http){
   return {
      fetch: function(searchQuery){
       return $http.get('http://192.168.100.100/myApp/items/'+searchQuery);
        }
        };
        });

Next, within your controller:

var promise = products.fetch(searchQuery);
promise.then(function(response){
// Implementation logic
$scope.itemsList = angular.fromJson(JSON.parse(response.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

Unexpected token < error encountered during parsing in jQuery Ajax long polling append

How can I create a real-time ticker similar to Facebook using Jquery Ajax long poll and PHP? I encountered an error in my script that displays "error parsererror (SyntaxError: Unexpected token <)". What could be causing this error in my code? Here is ...

Tips for removing or changing the X-Powered-By header in a Sails.js application

Running a Sails.js application results in the automatic addition of the HTTP header X-Powered-By: "Sails <sailsjs.org>" to every response. Is there a way to prevent or modify this header? ...

Exploring the concept of 'Abstract classes' within the Svelte framework

As someone who is relatively new to Svelte and frontend development (with primary experience in Rust/C++/Python), I hope you can forgive me for asking what might seem like a basic question. My goal is to showcase different kinds of time-indexed data, with ...

Does using .detach() eliminate any events?

I have a DIV that is filled with various content, and I am using the detach() and after() functions to move it around within the document. Before moving the DIV, I attach click events to the checkboxes inside it using the bind() function. Everything seems ...

Having trouble displaying a list in HTML using ngFor syntax

I'm relatively new to angular and front-end development. I'm currently trying to make a call to a REST API in order to fetch a list of products, and then display them on the HTML page. product.component.html <div class="page-title"& ...

Harness the power of electrons with the simple push of a button - initiating program execution

Recently, I delved into Electron with the desire to create a small application for myself. This app would allow me to run different programs or games by simply clicking on a link. My goal is to have the program/game start automatically when I open the Ele ...

Is there a way to delay the start of an ajax function until a few moments after the user

Good evening, I am interested in implementing a new feature using Ajax. Specifically, I would like to introduce a delay of 2 seconds after the user finishes typing before triggering the search function, as opposed to using "onkeyup". Note: This modificati ...

Fill a popup window with data retrieved from a MySQL query result

I have created an HTML page that displays data retrieved from a MySQL database. Users have the option to edit records, and I want to implement a modal form that opens up and shows data related to a specific "id" from the database when the edit button is cl ...

jquery sequential fade effect

I am trying to make each div fade in one by one. Visit this link for reference <div id="w"> <div class="one"></div> <div class="two"></div> <div class="three"></div> </div> $(function() { $(&a ...

Setting the selected value of a static select menu in Angular 2 form

I'm having an issue with my Angular 2 form that includes a static select menu. <select formControlName="type" name="type"> <option value="reference">Referentie</option> <option value="name">Aanhef</option> &l ...

Ways to clear the Yeoman index.html cache

Every time I update my Angular app, the old version continues to show up, requiring a "hard" refresh on the browser as a workaround (which is not ideal). My project uses Yeoman (generator-angular) and after examining the Gruntfile.js, I noticed that it re ...

Error: The parameter "callback" must be in the form of a function

Following a tutorial to upload images to Twitter using Node.js with Twit. Here is the code: function upload_random_image(){ console.log('Opening an image...'); var image_path = path.join(__dirname, '/random_cam/' + random_cam()), ...

What is the correct way to execute this script?

I am a beginner in javascript and I have a script that can delete a record without refreshing the page. However, I am unsure of how to call this script. Here is what I have so far: My button: <button id="<?php echo $rrr['id']; ?>" clas ...

Modal box fails to refresh content

Currently, I am in the process of learning how to modify my blog using a modal window. However, when I click on the edit button within the modal, an error message 'Failed to execute 'fetch' on 'Window': Invalid name' appears i ...

Efficient management of jQuery variables

I am currently working on a form and I have been trying to change an input's type using jQuery. Thanks to the helpful resources available on this website, I learned that I need to clone and replace the input in order to change its type. However, I enc ...

Ways to retrieve the complete user object in passport

Recently, I've been diving into utilizing Express authentication with Passport and React for the frontend. While working on this project, a question came up: How can I access the entire authenticated user object? This is what my database model looks l ...

Show InfoWindow on Google Maps by hovering, not clicking

I have a query about integrating Google Maps with a jquery plugin for map display. Everything is functioning correctly, from marker positioning to page reload (with new database queries based on updated map coordinates, etc.) The only issue I'm faci ...

Overlap of sub menus

Seeking assistance from a CSS expert for a challenge I am facing. I am currently working on a toggle menu for mobile view, and encountering issues with the submenu. Any list item placed below another one with children is not visible. Removing the parent l ...

How to implement dynamic aggregate functions with parameters in Express and Mongoose

I have implemented an aggregate function in mongoose to fetch some data, with a static implementation. app.get("/male",function (req,res) { Record.aggregate([ { $match: {"gender": "male"} }, { $group:{ _i ...

"Auth.currentSession is indicating that there is no user currently logged in

I am currently working on a basic React app with authentication using aws-amplify. My user pool is set up in Cognito and I can successfully redirect the user to the hosted UI for login. However, when trying to retrieve the current session, I am receiving a ...