AngularJS and TypeScript encountered an error when trying to create a module because of a service issue

I offer a service:

module app {
    export interface IOtherService {
        doAnotherThing(): string;
    }

    export class OtherService implements IOtherService {
        doAnotherThing() {
            return "hello.";
        };
    }

    angular.module('app').service('otherService', OtherService);
}

I have a custom controller:

module app {
    export interface IOtherController {
        performCustomActions(): string;
    }

    export class OtherController implements IOtherController {
        static $inject = ['otherService'];
        constructor(private otherService: IOtherService) { }
        }
    }

    angular.module('app').controller('otherController', OtherController);
}

I also created a routing file (using ui-router):

module app {
'use strict';

angular
    .module('app')
    .config(customConfig);

customConfig.$inject = ['$stateProvider', 'otherService'];
function customConfig($stateProvider, otherService) {
    $stateProvider
    .state('customState', {
        url: '/Dashboard/Welcome/',
        parent: 'dashboard',
        resolve: {
            otherValues() { return otherService.doAnotherThing(); }
        },
        views: {
            'content@': {
                    templateUrl: '/path/to/file/another.html',
                    controller: 'otherController',
                    controllerAs: 'vm'
            }
        }
    });
}

I keep encountering this error and I am unsure of the cause:

Error: [$injector:modulerr] Failed to create module app:
[$injector:unpr] Unknown provider: otherService

I realize my routing file is currently written in plain JavaScript, so please excuse the confusion compared to TypeScript examples.

EDIT: Made some corrections. Apologies for any mistakes from copy-pasting.

Answer №1

If you're looking for a solution, there is a working plunker available for reference.

The important thing to note is that we are restricted from requesting 'someService' injection during the .config() phase. At this point, only Providers can be injected and configured.

To work around this limitation, it's necessary to shift the dependency on a service directly to the resolver - like so:

someValues : ['someService', (someService) =>
... // This is where 'someService' should be requested as it will be executed in a .run() phase

angular
    .module('app')
    .config(config);

config.$inject = ['$stateProvider'];
function config($stateProvider) {
    $stateProvider
    .state('someState', {
        url: '/Home/Hello/',
        parent: 'home',
        resolve: {          
            someValues : ['someService', (someService) =>
                                        { return  someService.doSomething(); }]
        },
        views: {
            'content@': {
                    templateUrl:  'path/to/file/something.html',
                    controller: 'someController',
                    controllerAs: 'vm'
            }
        }
    });
};

To see this concept in action, check out the demo here

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

What could be causing my sinon test to time out instead of throwing an error?

Here is the code snippet being tested: function timeout(): Promise<NodeJS.Timeout> { return new Promise(resolve => setTimeout(resolve, 0)); } async function router(publish: Publish): Promise<void> => { await timeout(); publish(&ap ...

What is the term used for the objects that res.render passes?

I constantly find myself struggling with defining objects inside res.render. Is there a way to define them globally or outside of res.render? I hope someone can offer some guidance.. here is a sample code snippet: router.get("/home/blog", function(req,r ...

The Firebase JQuery .on method is incrementally updating individual values in an array instead of updating them all simultaneously

I am trying to update the values of the orders placed by users on the Corporate's page without a refresh. I have implemented the jQuery .on method for this purpose. However, the values are being returned one by one from the array created for the order ...

Error: Unable to modify the value of a protected property '0' in the object 'Array'

I am facing a challenging issue with implementing a Material UI slider in conjunction with Redux. Below is the code for the slider component: import { Slider } from '@material-ui/core' const RangeSlider = ({handleRange, range}) => { ...

Issues encountered when setting up a Context Provider in React using TypeScript

I am currently in the process of setting up a Cart context in my React TypeScript project, inspired by the implementation found here: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js. I'm encountering some conf ...

Implement a jQuery feature to gradually increase opacity as the user scrolls and the page loads

On a dynamically loaded page via pjax (except in IE), there are several links at the bottom. Whenever one of these hyperlinks is clicked, the page scrolls to the top while still loading. Although I am okay with this behavior, I'm curious if it' ...

``If you're looking to integrate a 360-degree product viewer into your Angular application, here is a

I am in need of showcasing a 360 Product viewer consisting of an array of 36 car images in base64 format. Despite attempting to utilize the angular-three-sixty Package by @mediaman, I was only met with an empty canvas. Does anyone have experience in implem ...

Ways of converting a negative lookbehind into an ES5-friendly expression

In my code, I have a RegExp that works perfectly, but it only functions with ES2018 due to its use of negative lookbehinds. The problem is that a library is using this RegExp function, so modifying how it's used is not an option. I attempted to add n ...

Trouble accessing onclick function

My dataSend AJAX function is not being called when I use the onclick event. I have checked in the Inspector of my browser and confirmed that the click handler is attached to it. However, when I set a breakpoint in the function using the Debugger, it never ...

Having difficulty loading Angular2/ Tomcat resources, specifically the JS files

I am currently in the process of deploying my Angular2 web application on a Tomcat server. After running the ng build command, I have been generating a dist folder and uploading it to my Tomcat server. However, whenever I try to run my web app, I encounte ...

What is the correct way to have Material-UI's <TextField/> component return with a ref attribute, similar to <input/> in ReactJS?

Using this particular method: handleClick(event) { const inputText = this.refs.inputText console.log(inputText.value.trim()) } I am attempting to make Material-UI's <TextField/> return the input text accurately with a ref, similar ...

Having trouble getting the map function to work in ReactJs while using Next.js?

Hey there, I am diving into ReactJS with the "Nextjs" framework and working on fetching data using async functions. However, I am facing an issue where I am unable to fetch data using the map function. The console.log is displaying a message saying "item ...

Sending a POST request using Node.js Express: A step-by-step guide

Looking for help on sending a post request from node.js Express with data passing and retrieval. Preferably a straightforward method like cURL in PHP. Can anyone assist? ...

Implementing precise search functionality in a table with jquery datatables

Hey there, I'm attempting to implement an exact search feature in jQuery datatables. In my table, I have a column called "status" with values of either "paid" or "unpaid". Currently, when I type "unpaid", it correctly displays only the unpaid record ...

JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created. After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopu ...

Is it possible for me to use an NPX tool to execute git clone command?

I am currently working on developing a personalized NPX tool that will install my custom npm package onto a locally hosted server. At the moment, I have a layout template that I want other users to replicate when they run my NPX command. Here is an exampl ...

The name 'withStyles' is nowhere to be found

import * as React from "react"; import Button from "@material-ui/core/Button"; import * as PropTypes from "prop-types"; import {WithStyles} from '@material-ui/core'; import "./App.css"; import PageTwo from "./components/PageTwo"; ...

"Implementing a dynamic way to assign values to different item types in React

There is an object with multiple values inside: const [sort, setSort] = useState({ "city": [], "price": [], "year": [] }); When the "add" button is clicked, the "city" value should be updated to include certain va ...

Creating an AngularJS recursive tree that displays the path or depth of each node

My goal is to display a tree using AngularJS and include the full path for each node. Consider the following model: ... $scope.data = { nodes: [{ name: "Apple", nodes: [{ name: 'Mac', nodes: [{ ...

Customize your popover content with Bootstrap settings

I've been on a quest to dynamically update the content of a Bootstrap popover using JavaScript, but unfortunately, the methods I've tried so far haven't worked out as expected : <!--object with the popover--> <input id="popoverlist ...