Invoke an Angular service from a separate JavaScript file

I have a few javascript and html files: User.js, index.html, Door.js

I am looking to utilize a function in the User.js file.

I am trying to call the getUserInfo function from User.Js within the Door.js file, specifically within the doorApplicationLoginPage.service.

Error: [$injector:unpr] Unknown provider: UserServiceProvider <- UserService <- PerioMainController

var doorApplicationLoginPage = angular.module("PerioLoginPage", []);

doorApplicationLoginPage.service('UserService', function () {

    this.getUserInfo = function () {
        alert("getUserInfo");
    }

    this.reLoginUser = function () {
        alert("reLoginUser");
    }

});


var doorApplication = angular.module("PerioDoorApplication", []);

doorApplication.controller("PerioMainController", function ($scope, $http, $sce, UserService) {


    UserService.getUserInfo();

});

Thank you.

Answer №1

You've included a service that isn't connected to your module.

Consider the following:

The UserService service is associated with the PerioLoginPage module. The PerioMainController controller is linked with the PerioDoorApplication module.

To address this issue, you can:

  1. Add a reference to the service in the same module as your controller.
  2. Ensure the service module is injected into the module where the controller is located.

Answer №2

Looking at this scenario, it appears that there are two distinct modules named Periodicloginpage and periodicdoorapplication. Each module defines a specific service within its own scope. To ensure proper functionality, it is necessary to establish a dependency relationship by including the Periodicloginpage module as a requirement for the periodicdoorapplication module.

var doorApplication = angular.module("PerioDoorApplication", ["PerioLoginPage"]);

Answer №3

Like I mentioned earlier, there are a couple of tasks that need to be addressed:

Firstly, make sure to return the functions you intend to use from the service (UserService):

return{
    getUserInfo: getUserInfo, 
    reLoginUser: reLoginUser
};

Additionally, your module must reference the one where the service is defined:

angular.module('PerioDoorApplication', ['PerioLoginPage']);

When writing your 'PerioMainController', a more efficient approach would be:

doorApplication.controller('PerioMainController', ['$scope', '$http', '$sce', 'UserService', 
    function($scope, $http, $sce, UserService){
        [...]
    }
]);

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

Guide on passing a variable from AJAX response to a JavaScript function when a user clicks

I need to send the value of a variable as a parameter to a javascript function when clicking on a link. The value is obtained from an AJAX response. However, I am encountering an error in the console stating that 'test' is not defined. var test ...

Sleek descending motion effect

I have created a simple function, but it is not animating smoothly and seems to lag... I am using it for a div sized at 1600x700 pixels on page load $(document).ready(function(){ $('#slider').slideDown(500); }); Is there any way to ensure s ...

In Angular 7, where can the controller be found within its MVC architecture implementation?

From what I understand, Angular adheres to the MVC architecture. In the components, there is a .ts file which serves as the model and a .html file for the view, but my question is: where is the controller located? ...

Discover the correct steps to transition from using particles.js to the react-tsparticles package

Migrating from react-particles-js to react-tsparticles-js Hi there! I'm currently facing an issue with my ReactJS website here, which is deployed using Netlify. The error code below keeps popping up, and I believe it's related to the transition ...

Tips on slowing down the Jquery UIBlock Plugin

Currently, I am implementing a plugin found at http://jquery.malsup.com/block/#overview. However, I am interested in configuring the blockUI feature to only be displayed if an AJAX request takes longer than 1 second. Otherwise, I would prefer for nothing ...

Got a value of `false` for an attribute `closable` that is not meant to be a

Here's the code snippet I have: import { Modal } from "antd"; import styled from "styled-components"; export const StANTModal = styled(Modal)` & .ant-modal-content { border-radius: 20px; overflow: hidden; } `; And ...

Encountering an issue with retrieved items upon refreshing the webpage

My usual approach to fetching data from an external API involves the following steps: Using Fetch API: const [tshirts, setTshirts] = useState([]); const fetchData = () => { fetch('apiEndpoint') .then((response) => ...

When working with Vue, setting the default value for props as a computed property is an

props: { rules: { type: Array, required: false, default: () => [ (file) => !file || file.size < 10000000 || this.getJsonDataByLocale.less_than_10mb_message, (file) ...

What could be causing the npm mysql module to malfunction when trying to initiate the 'connect()' function in a separate .js file?

When I call require('mysql') and use the function connect() everything works fine. However, if I try to call the 'connect()' function in another file, it throws an error saying connection.connect is not a function... Any suggestions on ...

Is it possible to switch out all instances of "GET" methods with "POST" throughout the codebase?

While working on a web application, we encountered caching issues with Internet Explorer (caching occurred due to the use of GET requests). The problem was resolved when users turned on "Always refresh from server" in IE's Developers Tool. Although we ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

Exploring CSS animations by utilizing the transform and color properties

I am currently working on a project that involves animating text (specifically "happy birthday to you") and a heart. The idea is for the heart to drop and hit each word one by one, turning them yellow upon impact. Once the last word is hit, the text shou ...

Having difficulty positioning the Divider correctly among Grid items

I am trying to add a Divider between each item in my Grid. The desired output should resemble this:- Col 1 | Col 2 | Col 3 However, I am facing difficulties as the Divider is not visible and the items are displayed vertically. import "./style ...

Executing multiple requests simultaneously with varying identifiers following a waiting period

I am looking to send a GET request using the user_id key retrieved from the userData object. This is how the request should be structured: Let's assume we have userData defined as follows: var userData = [ { id: 1, user_id: ...

How to Utilize findIndex to Validate the Presence of Elements in an Array of Objects using TypeScript

I need assistance in checking which properties from an array are present in another array of objects and which ones are not. My object structure is as follows: var tempObj=[{id: '1', color: 'red, blue, green', age: 27},{id: '2& ...

JavaScript embedded within LD-JSON format

Is it feasible to run JavaScript code within an ld+json script? Like for instance, "window.location.hostname" <script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebSite", "url": "http://" + window.location.ho ...

Are there any find all functions available in JavaScript that are built-in?

I frequently work with arrays in JavaScript, and I am facing an issue with the function .find() as it only returns the first occurrence. I need a way to get all occurrences if there are multiple. Below is my code: const condition = [ { info_p ...

CircularProgress Error: Unable to access 'main' property as it is undefined

As I delve into the realm of React and Next.js, I am faced with the task of upgrading from Node V16 to Node V18. One significant change in this upgrade is migrating from MUI v4 to v5. Currently, my project utilizes the following packages: "@emotion/ba ...

Tips for effectively managing asynchronous tasks

I keep getting different numbers every time my code runs. Can you tell me if I'm doing this the right way? Here's the code: export class GetPlanetsService { url='https://swapi.co/api/planets/?page='; planets:Planet[]=[]; headers: ...

Troublesome update: Migrating XState's Reddit example from Vue 2 to Vue 3

Recently, I delved into the XState documentation and decided to explore the Reddit sample provided in the official guide. You can find it here: As I attempted to upgrade the sample implementation to Vue 3 following the work of Chris Hannaby, I encountered ...