Error message "Unknown provider: $stateParams encountered when utilizing ui-router's resolve function in Typescript"

I am facing a challenge in converting an Angular ui-router configuration file with multiple states and resolves to Typescript. Everything seems to work fine until I introduce the $stateParams, which leads to the 'Unknown provider' error. I have tried including the $stateParams dependency in various places such as the $inject, constructor, .config(), and resolve function as shown below:

interface IMyStateParams extends ng.ui.IStateParamsService {
    parentObjectId: Guid;
}

export class listConfig {
    $inject = ['$stateProvider', '$urlRouterProvider', '$stateParams', '$qmcPath'];

    constructor(private $stateProvider: ng.ui.IStateProvider, private $urlRouterProvider: ng.ui.IUrlRouterProvider, private $stateParams: IMyStateParams, private $qmcPath: string) {
        this.init();
    }

    private init(): void {
        this.$stateProvider
            .state('client', {
                url: '/client/:parentObjectId',
                views: {
                    'main': {
                        templateUrl: 'MainDetail/',
                        controller: 'ClientDetailController',
                        controllerAs: 'detailCtrl'
                    }
                },
                resolve: {
                    clientDetailService: 'clientDetailService',
                    client: (clientDetailService, $stateParams) => {
                        return clientDetailService.getClientDetail(this.$stateParams.parentObjectId)
                            .then(function (data) {
                                return data;
                            });
                    },
                    clientWVs: function (clientDetailService) {
                        return clientDetailService.getClientDetailWVs()
                            .then(function (result) {
                                return result;
                            });
                    }
                }
            });
        }
    }
}

(() => {
    angular
        .module('QMC.Klient.List')
        .config(['$stateProvider', '$urlRouterProvider', '$stateParams', '$qmcPath', // more dependencies
            ($stateProvider, $urlRouterProvider, $stateParams, $qmcPath) => {
                return new QMC.Klient.List.listConfig($stateProvider, $urlRouterProvider, $stateParams, $qmcPath);
            }
        ]);
})();

What is the correct way to include a dependency like that?

Ps. I also attempted using this.$stateParams with the same outcome.

Answer №1

One approach could be to eliminate all dependencies related to $stateParams, focusing only on the parameter within the resolve-function

Answer №2

It's not entirely clear what the issue is here because at first glance, everything seems to be correctly structured. One potential problem is that the class defines $inject as a property on the object before it is actually set during construction.

// Correct
function MyObj(a, b, c) {}
MyObj.$inject = ['a', 'b', 'c'];

// Incorrect
function MyObj(a, b, c) {
  this.$inject = ['a', 'b', 'c'];
}

To resolve this, there are several solutions available. One effective approach would be to utilize a decorator, which can streamline the process and enhance code readability.

@injectable
export class listConfig {
    constructor(private $stateProvider, private $urlRouterProvider, private $stateParams, private $qmcPath: string) {}
}

function injectable(target) {
    var fnStr = target.toString().replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, '');
    var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(/([^\s,]+)/g);
    if(result === null) {
        result = [];
    }

    target.$inject = result; 
}

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

Issue: Unable to locate 'child_process' module in Angular-cli

After creating a new application with angular-cli and adding components, I encountered an error when trying to run/build the application without any test cases included. The error message received was quite lengthy: ERROR in ./node_modules/selenium-webdri ...

Angular JS now powers Assemble, the static site generator

I am interested in building a website with the help of Assemble, Yeoman, and AngularJS. My idea is to have Assemble manage content, while AngularJS handles dynamic content through a REST API. I am wondering if these two technologies are compatible and if ...

Manipulating input dates in AngularJSIn AngularJS, we can easily set the value

I'm having trouble setting a date field in my code. Despite trying to follow the example provided in the AngularJS documentation, nothing is showing up in the "departure" field. Here is what I have: HTML: <input type="date" name="departure" ng-mo ...

The Axios function is unable to read the 'Ok' value because of undefined properties

I suspect there is something missing in my argument, but I am attempting to call HttpStatusCode.Ok from the Axios Enum. Here is how I have implemented it: import { HttpStatusCode } from 'axios' console.log(HttpStatusCode.Ok) However, I encounte ...

Running cy.task after all test suites can be done by adding the task in a

I need some guidance on running cy.task after executing all test suites. I have a file generated at the start of the tests that I would like to remove once they are completed. Regardless of whether any tests passed or failed, I want to trigger cy.task im ...

AngularJS - connecting to resize directive

Is there a way to receive notification when a directive is resized? I've attempted the following: element[0].onresize = function() { console.log(element[0].offsetWidth + " " + element[0].offsetHeight); } However, the function is ...

What is the process for bringing my API function into a different Typescript file?

I've successfully created a function that fetches data from my API. However, when I attempt to import this function into another file, it doesn't seem to work. It's likely related to TypeScript types, but I'm struggling to find a soluti ...

Is there a lack of control when it comes to using AngularJS

While I continue to enhance my AngularJS skills, I find myself questioning the level of control I have with less direct manipulation through JavaScript. Everything seems to be driven by bindings in the HTML code/attributes. How can I interact with $rootS ...

Is it possible for me to create a data type representing "potentially undefined strings"?

Just a heads up: I have enabled --strictNullChecks Here is a function I have: export function ensure<T, F extends T>(maybe: T | undefined, fallback: F): T { if (isDefined<T>(maybe)) { return maybe } if (fallback === undefined) { ...

Encountering error 127 when initializing the angular-seed application with npm start

Attempting to configure the angular-seed application. Nodejs installation completed using sudo apt-get install nodejs Npm installed with sudo apt-get install npm Bower installation done with sudo apt-get install bower -g Nodejs-legacy installed with su ...

Using local variables from an external HTML file within an AngularJS directive template

Just making sure I am wording my question correctly, but I have not been able to find any information on this specific topic. Imagine I have an AngularJS directive that looks something like this: angular.module( 'example', [] ).directive( ...

How can I prevent an Angular filter from duplicating an array

Encountering an issue with my Angular code. Attempting to filter an array using the Angular filter service, but instead of selecting each element in the array, it duplicates. I have experimented with 'track by' but it does not resolve the proble ...

Learn how to dynamically add comments to HTML elements in AngularJS

Here is the meta tag that I have: <meta title='raja' identifier> I would like to know how to manipulate the DOM so it looks like this: <!-- reference <meta title='raja'> --> Could you recommend a way to manipulat ...

Encountering Syntax Errors during Angular 6 production build

I encountered an issue with my project. Everything was running smoothly, and even when I executed the command ng build --prod, it compiled successfully and generated the dist folder in my project directory. However, after copying this folder to the htdoc ...

Oops! An error has occurred while attempting to differentiate '[object Object]'. Please note that only arrays and iterables are permitted in Angular

I'm encountering an issue while attempting to showcase data from my JSON file. Despite extensively researching on StackOverflow, I am unable to find a solution to the error at hand. The error message reads: Error trying to diff '[object Object]& ...

The React-Native module cannot be resolved and is showing as undefined

I've been attempting to import a custom TypeScript class and initialize it for use with my view components. However, I encountered an error when trying to initialize the class: Error message displayed in emulator My import statement looks like this: ...

`How can I eliminate all duplicate entries from an array of objects in Angular?`

arr = new Array(); arr.push({place:"1",name:"true"}); arr.push({place:"1",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"2",name:"false"}); arr.push({place:"3",name:"false"}); arr.push({place:"3",name:"true"}); I'm curious about ...

Navigate to a different directory within Cypress by utilizing the cy.exec() function

Dealing with cypress to execute a python script in another directory. However, it seems like the directory change is not functioning as expected. visitPythonProject() { cy.exec("cd /Users/**/Desktop/project/"); cy.exec("ls"); // thi ...

Arranging an array in ascending order using Angular JS upon page load

How can I easily organize the following array in ascending order when the page loads: <div ng-init="fruits=['apple','orange','mango','banana','pineapple','kiwi']"> I attempted the followin ...

The Angular datepicker is failing to trigger the ng-change event

I've run into a snag with the datepicker and ng-change functionality. Oddly enough, the ng-change event isn't triggering when I manually select a date by clicking on it, but it works fine when I input a date manually. Take a look at my code snip ...