a service that utilizes $http to communicate with controllers

My situation involves multiple controllers that rely on my custom service which uses $http. To tackle this issue, I implemented the following solution:

.service('getDB', function($http){
   return {
      fn: function(){

        return $http({
            url: "http://example.com",
            method: "GET"
        });

      }
   }
})

.controller('myCtrl', function($scope, getDB) {
console.log(getDB.fn());
}

Upon checking the output of getDB.fn() using console.log, I noticed that it returns $promise. How can I access the response data from this?

Answer №1

When working with $http in AngularJS, it returns a promise which can be further understood by referring to the $q documentation.

To utilize the promise, follow these steps:

.controller('myCtrl', function($scope, getDB) {
    getDB.fn(something).then(function(result){
         // Access the result here
    }, function(error){
         //Handle errors here
    });
}

You can pass parameters in the following way:

.service('getDB', function($http){
 return {
   fn: function(something){

    return $http({
        url: "http://example.com/" + something,
        method: "GET"
    });

   }
 }
})

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

Does the onwheel event get triggered when scrolling on a trackpad?

Despite being a fundamental inquiry, the answer remains elusive to me. Due to its simplistic nature, there isn't much of an elaborate explanation available. Regrettably, I am lacking access to a laptop for testing purposes. ele.onwheel = function(e) ...

Extract string data from JSON payload

How can I extract the itemlocation from itemInfo and display it in a new column in my react table using Material UI? While I know this can be done on the backend, I am looking for a way to achieve this without backend involvement. Below is an example of ho ...

Arrange the Json array by key value in a different order

I have a contact list that is returning in a lengthy form, organized based on order of entry. I am looking to alphabetically sort the list by displayName which is nested within the main array. Can anyone assist with this challenge using JavaScript? Thank ...

Troubleshooting Next.js Mobile Freeze Issue: Unresponsive Scroll After Page Transition

Encountered a strange bug while testing my Next.js + Bootstrap demo project on mobile view. When using the burger menu to navigate to a new page on a mobile phone, attempting to scroll down causes it to stick/freeze/hang inexplicably. Despite my efforts to ...

Unexpected Issue Encountered in JQuery Integration

I recently added jQuery to my HTML file: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script> After that, I included a link to my JavaScript file: <script src="public/javascripts/new_javascript.js" type ...

Utilizing AngularJS ng-show to conditionally display content based on data retrieved from an

I am facing an issue with implementing the ngShow directive in my code, where I am trying to display data fetched from an API call. However, despite everything else working correctly, the ngShow directive does not seem to be functioning as expected. Here ...

JQuery click event does not play nicely with Javascript array splice functionality

When using for loops, I noticed that array.splice doesn't seem to be working as expected. The array remains unchanged. I tried moving things around and found that it still doesn't work in Chrome. var menu =['#men','#wmen',&a ...

Positioning 3D objects in Three.js

I am working on a 3D Scene using Three.js with an Earth shape that currently looks like this: https://i.sstatic.net/zXWki.png My goal is to modify it to resemble something like this: https://i.sstatic.net/w4ypV.jpg The coloring, stars, and texture are ...

The validation process did not pass because of a manually inputted value

When a user selects a file, the filename value is automatically inserted into the fileName field. However, the validation fails because the field is still considered empty until at least one more character is added. How can I fix this issue? This is how t ...

I am attempting to activate the "about us" button on the website. I have successfully included the path and added a router link to the containing div of the button. However, there seems to be something

In my app, the first step involves specifying the path in the routing module. Following that is defining the home component, then the app component, and finally creating the button using HTML. Setting up the path in the app.routing.module.ts file <div ...

What is the best way to execute a sequence of consecutive actions in a protractor test?

To achieve logging in, verifying, and logging out with multiple users, I decided to use a loop. I came across a helpful post that suggested forcing synchronous execution. You can find it here. Below are the scripts I implemented: it('instructor se ...

Increasing the size of elements with jQuery animate method

I've been utilizing the animate function in jQuery to dynamically resize a content area upon hovering over the element. Although the script is functioning correctly, I'm facing a challenge in preventing the script from resizing the content multi ...

Looking for a script that automatically swaps out a div at set intervals? You'll need to tweak it so that it only

I created a js script that dynamically changes the content of certain div elements at specified intervals. While I appreciate how it functions, I now need to modify it so that the script only executes once. Can someone help me achieve this? <script typ ...

When attempting to send an array value in JavaScript, it may mistakenly display as "[object Object]"

I queried the database to count the number of results and saved it as 'TotalItems'. mysql_crawl.query('SELECT COUNT(*) FROM `catalogsearch_fulltext` WHERE MATCH(data_index) AGAINST("'+n+'")', function(error, count) { var ...

AngularJS - fetch array length from a webApi request only on the initial call

I'm looking to display the text 'showing X of Y Attractions' where X represents the current number being displayed and Y is the total number stored in the database. Obtaining X is easy with {{Attractions.length}}, but I'm unsure of the ...

Using Vue's V-IF directive to compare dates

On my website, I have an object that contains a field named available_at with the date in the format of 2019-08-08 I have a working HTML table utilizing Vue bindings but I am unsure how to compare the timestamp above using the built-in Date.now() method ...

Preventing users from copying and pasting information from my form by implementing javascript restrictions

I'm looking for a solution to prevent users from copying and pasting in my form using JavaScript. I want to restrict the ability to paste or copy any content into the form. Any assistance would be greatly appreciated! ...

Implementing Date.now() as a Schema Field Type in Meteor's Simple-Schema

Within my Meteor application, I have utilized Date.now() to generate a timestamp for inclusion in a new MongoDB document. Although Date.now() appears to be an appropriate choice for my app, I lack expertise in managing dates and times. As I transition to ...

Tips for extracting unique values from two arrays and returning them in a new array using JavaScript

Hello, I need assistance with combining two arrays. Array a contains [1,2,3] and array b contains [2,5]. I would like the result array to only include elements that are unique between the two arrays, such as [5]. Can you please provide guidance on how to ...

What is the best way to retrieve the promise that encountered an error in the catch block while using async/await

I'm currently in the process of converting code that used .then/.catch to instead use async/await. One particular challenge I'm facing is how to access the original promise that fails within the catch block, for logging purposes. Here is the ori ...