Promise not being returned by AngularJS service function

I'm still getting the hang of Angular so if you need more information, just let me know and I'll update it here.

So I have a controller that's supposed to call a function from a service which should return some data fetched through an HTTP.get request. However, at the moment, it's not returning any data or promise.

Here's the controller code that's making the call to the service and handling the data:

var onRecentBlogPosts = function(data) {
    $scope.recentBlogPosts = data;
    $log.info($scope.recentBlogPosts);
    $log.info(JSON.stringify($scope.recentBlogPosts));
}

var onError = function(response) {
    $('.error-container').html("<div class='messages error'>Could not fetch the data. <br /><br />More information: <br />"+response+"</div>");
}

$q.when(backend.getRecentPosts).then(onRecentBlogPosts, onError);

I also tried:

backend.getRecentPosts.then(onRecentBlogPosts, onError);
//but then I get the error
TypeError: backend.getRecentProjects.then is not a function

The function in the 'backend' service being called is getRecentPosts

Service code:

(function() {
var backend = function($http, $q) {
    var getRecentPosts = function() {
        return $http.get("http://example.com/blog")
                    .then(function(response) {
                        return response.data;
                    });
    };

    return {
        getRecentPosts: getRecentPosts
    };
};


var module = angular.module("moduleName");
module.factory("backend", backend);

}());

When I check the console (after the lines executed in the success function), I see:

function getRecentPosts()
undefined

My main question is how do I structure my service and service functions to be able to call them from various controllers and receive both a promise and data?

Answer №1

backend.retrieveRecentPosts().then(displayRecentBlogPosts, handleErrors);

It appears that you have overlooked executing the function. Additionally, there is no requirement to include the 'then' method within the factory.

var retrieveRecentPosts = function() {
        return $http.get("http://example.com/blog")
};

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

The connection between the layout of dropdown menus and the way data is handled in forms

I have discovered three different methods for creating dropdowns that can be used in forms: 1) Utilizing HTML with "form-dedicated" attributes such as select and option value="" 2) Implementing the Bootstrap framework with div classes like "dropdown", Butt ...

Why do I have to press the button twice for it to actually work?

I am new to programming and I want to create something that has 3 buttons to control the display of 3 hidden images respectively. When I click the first button, the image appears immediately, but I have to click it twice to show the second image. Can anyon ...

Unable to establish a connection with the endpoint

I'm encountering an issue while trying to connect to the endpoint on the server. Below is the code snippet: Register.jsx function Register() { const [registerUser, setRegisterUser] = useState({ username: "", email: "", password: "", ...

What is the best way to transfer variables in my specific scenario?

As I consider the optimal approach for managing my controllers, I find myself faced with a challenge of passing data between them. In my setup, I have multiple controllers that require sharing data throughout. For the first controller: app.controller(&a ...

Implementing setInterval() leads to the dynamic alteration of images

I've created Marquees using CSS animations and a countdown timer. The Marquees display 100 random images that move from left to right and right to left. However, when the countdown timer decreases, the images in the Marquee change but the scrolling co ...

Angular integration of Jquery UI datapicker with read-only feature

Having trouble using ngReadonly within a directive, my code isn't functioning as expected: app.directive('jqdatepicker', function() { return { restrict: 'A', require : 'ngModel', link : functi ...

How to create a continuous loop for a JavaScript carousel

I have a simple carousel set up with this code. I'm looking to make it loop back to the beginning after reaching the third quote-item. Can anyone provide some guidance? Thank you! This is the JavaScript used: <script> show() $(functi ...

Leverage the JSON data to populate the category axis in c3.js

I have a JSON object that contains an array called datas, which holds the data I need to use for my chart. I want to utilize the data1 array for the x-axis in a category format. How can I achieve this? This is my attempted solution, where I extract the da ...

Attempting to display numerous react components on various divs instead of just one ID

Currently, I am facing a challenge in creating multiple react comment boxes. The package I am using is based on #id instead of class, which resulted in only rendering one box instead of all. To resolve this issue, I attempted to switch from GetelemntbyID t ...

Adding jQuery content to a div that is being created dynamically

Currently implementing a save/load feature using JSON for a diagram that utilizes jsPlumb. While the save functionality is working perfectly, the load functionality is encountering difficulties in replicating the full initial saved state. The issue arises ...

When utilizing express-formidable to retrieve multipart data, it causes basic post requests with request body to hang indefinitely

app.js const express = require('express') const app = express() const appInstance = express() const PORT = process.env.SERVER_PORT || 8080 app.use(express.json()) app.use(express.urlencoded({ extended : true })) app.use(formidableMiddleware ...

Having trouble with creating SQLite tables using JavaScript within a for loop

I have developed a multi-platform app using AngularJS, JavaScript, Phonegap/Cordova, Monaca, and Onsen UI. In order to enable offline usage of the app, I have integrated an SQLite Database to store various data. After conducting some basic tests, I confir ...

Having trouble with GLB file loading in three.js?

My GLB file is not displaying in my Three.js world. Despite following all the documentation and tutorials, the model is not showing up. The world loads perfectly and everything works fine, except for the model not appearing. I am on a journey to create a ...

Place a Three.js scene within a jQuery modal dialogue box

I am attempting to integrate a Three.js scene into a jQuery modal window. The objective is to utilize the Three.js scene in a larger window size. This scene should be displayed after clicking on an image that represents the scene in a smaller dimension. Y ...

What is the best way to show JavaScript output with span style?

I have added a translation feature that allows users to switch paragraphs to French when clicked. Each paragraph now has the first word wrapped in a span with a CSS class that enlarges and colors the text. However, I am facing an issue where when switchi ...

What is the appropriate content-type to use when sending AJAX POST data?

Having an issue sending base64 image data using ajax post. I suspect the problem lies with the Content-Type value, as I have tried using application/json, text/json, and image/jpeg without success. Javascript function sendFormData(fD) { var urls = fD ...

Modify the file format depending on the browser being used as Internet Explorer

Currently seeking the most effective method to dynamically alter the file extension of certain images (from .svg to .png) specifically for Internet Explorer users. Uncertain about the optimal approach: consider parsing the HTML code with PHP utilize jQu ...

Tips for resetting the mapbox geocoder

Using the Mapbox Geocoder along with multiple select menus to customize a map has been my latest project. I am currently working on resetting the geocoder once a user selects an option from the menu, clearing the input field and removing the marker in the ...

Determine the status of all jqXHR requests within an array to confirm completion

My goal is to execute a block of code once all the jqXHR elements in an array have completed, whether they have succeeded or failed. For the full code, you can check it out here: http://jsfiddle.net/Lkjcrdtz/4/ Essentially, I am anticipating the use of t ...

disable angular ui router functionality for specific links

Currently, I am looking to implement the bootstrap accordion in my Angular application. The angular ui-router is being used for navigating through different pages. However, I have come across an issue where the accordion requires an <a href="#Collaps ...