Error: UserService (?) is missing parameters and cannot be resolved

Upon compiling my application, an error is appearing in the console:

Uncaught Error: Can't resolve all parameters for UserService (?)

Despite having @Injectable() present for the UserService, I am unsure where to troubleshoot further.

import {Injectable} from '@angular/core';
import {Observable} from "rxjs";
import {UserModel} from "../../model/user.model";
import {environment} from "../../../environments/environment";
import {HttpClient} from "@angular/common/http";


@Injectable()
export class UserService {

  constructor(
    private _http: HttpClient
  ) {
  }

  getMe(): Observable<UserModel> {
    return this._http.get<UserModel>(environment.adminApiUrl + '/me');
  }
}

The necessary modules should be included in the app.module.ts:

import {BrowserModule} from '@angular/platform-browser';
import {Injector, NgModule} from '@angular/core';
import {AppComponent} from './app.component';
import {AppRouting} from "./app.routing";
import {BrowserAnimationsModule} from "@angular/platform-browser/animations";
import {LoggerModule, NgxLoggerLevel} from "ngx-logger";
import {environment} from "../environments/environment";
import {AuthGuard} from "./service/guard/auth.guard";
import {UserService} from "./api/service/user.service";
import {CommonModule} from "@angular/common";
import {setAppInjector} from "./app-injector";
import {HttpClientModule} from "@angular/common/http";

const ApiServices = [
  UserService
];

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    CommonModule,
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,

    AppRouting,

    // Logging
    LoggerModule.forRoot({
      serverLoggingUrl: '/',
      level: environment.production ? NgxLoggerLevel.OFF : NgxLoggerLevel.TRACE,
      serverLogLevel: NgxLoggerLevel.OFF
    }),
  ],
  providers: [
    AuthGuard,
    ApiServices
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

Despite these configurations, the error persists.

What could be causing this issue?


If I remove private _http: HttpClient from the constructor within UserService, the application functions normally. It seems like the @Injectable() annotation may not be functioning correctly in my current setup.

Answer №1

While browsing through GitHub, I stumbled upon an interesting issue titled "Angular 8: Can't resolve all parameters for Component: (?)".

Important to Note: It's worth mentioning that I am currently using Angular 7.

The suggestion provided was to include the following line:

"emitDecoratorMetadata": true,

within the tsconfig.spec.json file. Surprisingly, it only resolved the issue when I added the same line in the tsconfig.json as well:

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "module": "esnext",
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2015",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2018",
      "dom"
    ]
  },
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "emitDecoratorMetadata": true,
    "outDir": "./out-tsc/spec",
    "types": [
      "jasmine",
      "node"
    ]
  },
  "files": [
    "src/test.ts",
    "src/polyfills.ts"
  ],
  "include": [
    "src/**/*.spec.ts",
    "src/**/*.d.ts"
  ]
}

Upon revisiting my older projects, I noticed that emitDecoratorMetadata was consistently set to true. The project mentioned above was created by executing ng new <project-name> which resulted in the following Angular CLI version info:

$ ng --version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 8.3.21
Node: 10.15.2
OS: linux x64
Angular: 
... 

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.803.21
@angular-devkit/core         8.3.21
@angular-devkit/schematics   8.3.21
@schematics/angular          8.3.21
@schematics/update           0.803.21
rxjs                         6.4.0

Answer №2

Just wanted to share my experience - I faced a similar challenge during the transition from Angular 8 to Angular 9.

The root of the problem lied within the NGXS state implementation.

In my code snippet, I failed to include the @Injectable annotation.

@State<ActiveFiltersStateModel>({
  name: 'filterAdapters',
  defaults: {
    filters: {}
  }
})
@Injectable()
export class ActiveFiltersState {

  constructor() {
  }
}

https://i.sstatic.net/Tczvh.png

The team at Angular has put in significant effort to ensure that Ivy is compatible with the previous rendering engine ("View Engine"). However, some adjustments are necessary for NGXS and Ivy to work seamlessly together.

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

Can a universal type be designed for application across various types?

I've got this function: function stackPlayer(stack){ } The stack parameter can have one of the following forms only: a function that takes req, res, and next as arguments. a function that takes req, res, and next as arguments, and returns a functio ...

AWS Amplify is failing to maintain the user session post a successful login

Currently, I am developing an aws-serverless application using React. My main issue lies in the authentication process with aws-amplify. The authentication works smoothly, but the session is not being preserved. During the signing-in stage: await Auth.s ...

Display an error popup if a server issue occurs

I'm considering implementing an Error modal to be displayed in case of a server error upon submitting a panel. I'm contemplating whether the appropriate approach would be within the catch statement? The basic code snippet I currently have is: u ...

Diverse Selection of Font Awesome Icons

In my React project with TypeScript, I have a header component that accepts an Icon name as prop and then renders it. I am trying to figure out the best way to ensure that the icon prop type matches one of the existing FontAwesome Icons. import { FontAwe ...

Attempting to grasp the concept of Thennables within the VSCode API. Can these TypeScript code examples be considered equivalent?

I'm looking to perform a series of modifications on a document using the VSCode API. The key function in this process is Workspace.applyEdit, which gives back a Thennable. This is my first encounter with it, and the one returned from this function doe ...

Error message in TypeScript with Puppeteer library: "Element not found"

Incorporating puppeteer-core as a dependency in my TypeScript project within Visual Studio 2019 has caused an issue during the build process. The error message displayed is shown by a red squiggly line under Element: https://i.stack.imgur.com/HfJCu.png ...

Is it possible to activate ionViewWill/DidEnter from a tab navigating to an external page in Ionic/Angular?

I am attempting to initiate an event upon returning to my tab page from a page outside of the routing module. 2. I have experimented with: Employing @ionic/angular NavController from both pages: From the tab page: this.navCtrl.navigateForward([&apos ...

The Mat-paginator is refusing to align to the right edge when scrolling the table horizontally in an Angular application

Overview: My Angular component features a table with Angular Material's mat-table and paginator. Despite fetching data from a source, the paginator fails to float right when I scroll horizontally. Sample Code: <!-- Insert your code snippet below ...

When imported, Node / JS instantly generates a new instance

Is there a way to instantiate a class without importing it first and using new afterward? Instead of var mainClass = require('../dist/main'); // has "class Main { ... }" var mainInstance = new mainClass(); I am looking for something like var ...

Ordering an array using Typescript within React's useEffect()

Currently, I am facing a TypeScript challenge with sorting an array of movie objects set in useEffect so that they are displayed alphabetically. While my ultimate goal is to implement various sorting functionalities based on different properties in the fut ...

What could be causing the error message "why can't shows read property

Within my Ionic-Angular application, I have successfully loaded the content from the database and printed it on the console. However, I am facing an issue where I cannot bind this content to the view. The error message that appears is displayed in https:// ...

The useParams() function encounters difficulty in converting data to number typescript

Whenever I try to convert the heroId type from string to number in my code, I always encounter an error. Here is the code snippet: import useHero from '../../hooks/useHero'; import {useParams} from 'react-router-dom' function Herospag ...

Guide on integrating ng2-bootstrap with .NET Core

I have been attempting to set up ng2-bootstrap in an Angular2 project using the .NET Core template (more information about the template can be found here). However, I am facing difficulties as the ng2-bootstrap components are not functioning properly even ...

Arranging a 2D array of matchups to ensure an equal distribution of home and away matches for each team

I am in the process of developing a unique UEFA Champions League 24 'Swiss Model' tournament with 36 teams. Each team is set to compete against 8 different opponents, resulting in a total of 144 matches. I already have a list of matchups prepared ...

The requested resource does not have the 'Access-Control-Allow-Origin' header

Currently, I am working on an application that utilizes Angular for the client side and NodeJs for the backend. The application is being hosted with iis and iisnode. Recently, I implemented windows authentication to the application in order to track which ...

When using multiple select tags with *ngFor in Angular, modifying the value of the first select tag will have an

<table id="DataTable" border="1" ALIGN="center"> <tr ALIGN="center"> <th>name</th> <th>address</th> <th>number</th> <th>type</th> </tr> <tr class="tcat" *ngFor ...

Importing Typescript modules by specifying their namespace instead of using a function

I have been working on a project where I needed to generate typings from graphql using the gql2ts library. In the gql-2-ts file, I initially used a namespace import for glob, which resulted in TypeScript showing me an error as intended. I then switched the ...

"The latest version of Angular, version 15, experiencing issues with javascript loading

Currently, I am diving into the world of Angular and encountering a puzzling dilemma. Surprisingly, my application performs flawlessly on various browsers such as Chrome, Firefox, Brave, Opera, and even on mobile versions except for Safari. Both the deskto ...

Issue with TypeScript problemMatcher "$tsc-watch" not actively monitoring files in VSCode

I'm attempting to avoid the necessity of using watch: true in my tsconfig.json setup. Despite utilizing VSCode's tasks with the default problem matcher $tsc-watch, I am encountering an issue where tsc is not running in watch mode during the buil ...

Develop a structured type that encompasses the stationary attributes of an object-oriented class

Provided are the following classes: class EnumerationDTO { designation: string; id: number; } class ExecutionStatusDTO extends EnumerationDTO { static readonly open: ExecutionStatusDTO = { id: 0, designation: 'Open' }; static readonl ...