Is it possible to pass a service into another service in AngularJS?

I'm currently working on figuring out the best method for this task:

Our backend developer has requested a json file that contains a master list of api urls used in requests by my frontend. This will ensure that the end user's browser only needs to make one request for the object, which can then be passed into other services. For example...

The dataUrl JSON would look like this:

{
    "emails": "json/emails.json",
    "mapping": "json/mapping.json",
    "profile": "json/profile.json"
}

I need to store this as a variable that can be utilized in all my API calls, similar to the following:

app.factory('Emails', ['$http', function($http, Urls) {

    var url = ""; // code here to retrieve the dataUrl object for "emails"

    var query = {};
    query.getItems = function() {
        return $http.get(url.emails); // from the emails variable above?
    };
    return query;
}]);

What approach should I take to achieve this?

This is what I have attempted so far without success...

app.factory('Urls', ['$http', function($http) {
    var query = {};
    query.getItems = function() {
        return $http.get('json/dataUrls.json');
    };
    return query;
}]);

app.factory('Emails', ['$http', function($http, Urls) {
    Urls.getItems().then(function(response) {
        var url = response.data.emails;
        console.log(url);
    })
    var query = {};
    query.getItems = function() {
        return $http.get('json/emails.json');
    };
    return query;
}]);

This leads to a console error

TypeError: Cannot read property 'getItems' of undefined

Answer №1

You're injecting dependencies incorrectly

Make sure to inject before creating the instance

Give this a try:

Switch

app.factory('Emails', ['$http', function($http, Urls) {

to

app.factory('Emails', ['$http', 'Urls', function($http, Urls) {

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

Fluctuating CSS appearance during content loading and asynchronous CSS loading

As I work on loading a new page and a CSS file for it using AJAX, I encounter an issue. Once all the CSS files are added to the page, I set the opacity to 1, expecting the page to display with the CSS applied immediately. However, it initially appears wit ...

Converting a PHP array into JSON format and displaying the data on a webpage

I'm currently facing an issue with a Json Array. Here is my json data: { "res": ["000000000078", "00000001", "1367771147", "das ist mail text", "000000000080", "00000001", "1367771147", "das ist mail text", "000000000081 ...

Struggling with deserializing JSON using RestSharp

I am currently facing an issue with deserializing a JSON response from WooCommerce using RestSharp. Despite searching various sites for a solution, I have not been able to find one. Here is a simplified version of my JSON: [ { ...

Creating Dynamic Tables with jQuery

I have written a code to fetch values using jQuery and Ajax. The data is coming fine but I am facing an issue with populating the rows in my table. The loop doesn't seem to work properly. Here is my HTML table code: <div class="panel-body"> ...

I'm having trouble with certain JavaScript functions on my website - some are working fine, but others aren't. Any suggestions on what I should do

I just finished developing a calculator using HTML, CSS, and Javascript. It works flawlessly for all numbers 1 through 9 and the operators +, -, *, /, and %. However, I am facing issues with the number 0, C, and = buttons not functioning properly. Upon in ...

Can we avoid the error callback of an AJAX request from being triggered once we have aborted the request?

Initially, I encountered a challenge where I needed to find a way to halt an AJAX request automatically if the user decided to navigate away from the page during the request. After some research, I came across this helpful solution on Stack Overflow which ...

Determine the frequency of occurrences of a JSON property with a similar name

I am working on a Vue application that receives a JSON object as shown below. My task is to calculate the count of items where _Valid is set to true. I am not very familiar with the Reduce method in JavaScript and I'm unsure how to filter based on a s ...

Display sub navigation when clicked in WordPress

I currently have the default wordpress menu setup to display sub navigation links on hover, but I am interested in changing it so that the sub navigation only appears when the user clicks on the parent link. You can view my menu here https://jsfiddle.net/f ...

Node-fetch enables dynamic requests

Seeking to retrieve real-time data from a fast-updating API has posed a challenge for me. The issue lies in my code constantly returning the same value. I've experimented with two approaches: var fetch = require("node-fetch"); for(let i=0; i<5; i+ ...

Having trouble dismissing Bootstrap alerts in TypeScript?

There seems to be an issue with the close button in a simple piece of code. The alert is displayed correctly, but clicking on the close button doesn't close the alert. Currently, I am using bootstrap 5.2.3. My code consists of a basic main file and an ...

Verify whether the marker falls within the circumference of the circle using AngularJS

I am currently working on determining whether a specific marker falls within the radius of a circle. Additionally, I want to trigger an alert displaying the position of the marker when it is clicked. This functionality is being implemented using ng-map. V ...

Unable to set options, such as the footer template, in Angular UI Typeahead

I am looking for a way to enhance the results page with a custom footer that includes pagination. I have noticed that there is an option to specify a footer template in the settings, but I am struggling to find examples of how to configure these options th ...

Creating dynamic components in ReactJS allows for versatile and customizable user interfaces. By passing

Within the DataGridCell component, I am trying to implement a feature that allows me to specify which component should be used to render the content of the cell. Additionally, I need to pass props into this component. Below is my simplified attempt at achi ...

Troubleshooting problem in Java related to encoding with XMLHttpRequest

Currently, I am utilizing XMLHttpRequest for an ajax call to my server. Let's consider the call: http = new XMLHTTPRequest(); var url = "http://app:8080/search.action?value=ñ" http.open("GET",url,true); http.setRequestHeader("Content-type", "applica ...

What is the best way to toggle text visibility with a button click and what alternative method can be used if getElement does not work?

After successfully completing the HTML and CSS part, I hit a roadblock with JavaScript. I'm struggling to figure out how to create a button that can toggle the visibility of text when clicked. An error message keeps popping up in the console stating ...

Refreshing the MarkerCluster following an AJAX request

My current challenge involves an AJAX function that retrieves posts based on users with a specific role. While the query itself works fine, I am encountering an issue with refreshing the markers on Google Maps after the AJAX request is complete and the pos ...

Searching for a specific value within a list that has been fetched from a database using AngularJs can be achieved by simply clicking on the search button

Seeking assistance on a search functionality issue. I am able to filter search results from a list retrieved from the database and displayed on an HTML page, but facing difficulty in getting complete search results from the controller. When clicking the se ...

The instantiation of the cloudinary module failed because of an error with the injector

I am currently developing a MEAN application based on the template provided by Linnovate. You can find the template at https://github.com/linnovate/mean My goal is to integrate a module called Cloudinary into my application. To achieve this, I followed th ...

Encountering an error in React: Unable to access property 'elements' of undefined due to incorrect passing of the event object

Struggling to make a form submit text to send via axios to the backend API in React. Following an outdated tutorial and using antd library for the form template. Here is the current form code with some console logs to debug: import React, { useState } fr ...

I am implementing ng-options to display data in a dropdown menu, but I have a specific value "No-search" hardcoded in one of the options. How can I ensure that this value is

<div class="filter-box"> <select ng-model="$ctrl.customModel" ng-options='option.id as option.name for option in transactionstatusList' ng-change="transactionStatusChange()"> <option value="" s ...