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() {
  }
}

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

What steps can I take to resolve a dependency update causing issues in my code?

My program stopped working after updating one of the dependencies and kept throwing the same error. Usually, when I run 'ng serve' in my project everything works fine, but after updating Chartist, I encountered this error: An unhandled exception ...

Tips for effectively passing navigation as props in React Navigation with Expo

How can I correctly pass navigation as props to another component according to the documentation? The navigation prop is automatically provided to each screen component in your app. Additionally, To type check our screens, we need to annotate the naviga ...

What is the solution to prevent angular-material components from covering my fixed navbar?

After creating a navbar using regular CSS3, I incorporated input fields and buttons from angular material. However, my sticky navbar is being obscured by the components created with angular material. Here is the CSS for the navbar: position: sticky; top: ...

The types 'X' and 'string' do not intersect

I have a situation where I am using the following type: export type AutocompleteChangeReason = | 'createOption' | 'selectOption' | 'removeOption' | 'clear' | 'blur'; But when I try to compress the cod ...

Angular Universal functioning fine on local host, yet encountering issues on Nginx Server

I recently developed a project with Angular Universal. After building the project, it generated files such as browser, server, server.js, and prerender.js. I am curious to learn how I can run this project on an nginx server. Currently, I create a build o ...

Having trouble retrieving data from redux toolkit using typescript

I've been diving into the world of Typescript by building a simple todo app using React, Redux-toolkit, and Typescript. One issue I encountered is when trying to access data from the store with useSelector. The retrieved object contains the desired va ...

How can you ensure a code snippet in JavaScript runs only a single time?

I have a scenario where I need to dynamically save my .env content from the AWS secrets manager, but I only want to do this once when the server starts. What would be the best approach for this situation? My project is utilizing TypeScript: getSecrets(&qu ...

Should we use fakeAsync() or done() to handle asynchronous tasks

When creating an Angular test with Jest and dealing with asynchronous operations, do you have a preference for how to handle it? it('', fakeAsync(() => { // test code here })); or would you rather use something like it('' ...

Determining the type of an overloaded method within a generic function

I am currently working on developing a versatile function that can subscribe to an event emitter. The function subscribe is designed to take 3 arguments: event name, event handler, and the event emitter to connect to. I am looking for ways to ensure accur ...

Error Encountered: Angular 2 ngOnInit Method Being Executed Twice

Encountered an unusual error in Angular 2 while working on two components that share similarities in templates and services. Here is a breakdown of how they function: Component: data: any; constructor(private _service: TheService) {} ngOnInit() { t ...

Setting up grunt-ts to function seamlessly with LiveReload

I am currently experimenting with using TypeScript within a Yeoman and Grunt setup. I've been utilizing a Grunt plugin called grunt-ts to compile my TypeScript files, and while the compilation process is smooth, I'm encountering issues with live ...

The jsPDF tool captures only the visible frame in a screenshot instead of printing the entire content on the screen

Recently, I integrated the jsPDF npm module into my Angular application to convert HTML to PDF. However, I encountered an issue where printing a website page to PDF only captures a screenshot of the visible area in Firefox and Chrome, as well as in Interne ...

Incorporating an external TypeScript script into JavaScript

If I have a TypeScript file named test.ts containing the code below: private method(){ //some operations } How can I access the "method" function within a JavaScript file? ...

Trigger the React useEffect only when the inputed string matches the previous one

Currently, I am in the process of creating my own custom useFetch hook. export const useFetch = <T extends unknown>( url: string, options?: RequestInit ) => { const [loading, setLoading] = useState(false); const [error, setError] = ...

Utilizing PrimeNG Datatable to Connect with an Array of Objects in a Dynamic Manner

I currently have an array of objects with various properties such as: "rows": [ { "id": 1, "createdAt": "2017-07-21T06:05:38.000Z", "updatedAt": "2017-07-21T06:05:38.000Z", "createdBy": null, "modifiedBy": null, "name": "ABC", "owner": "Dian ...

checkbox causing the button to appear empty

Due to the inability of a ngIf and ngFor to coexist, I added an ng-container to facilitate the loop. However, after making this change, nothing seems to be working as expected without any clear reason. Below is the code snippet that is causing trouble: Vi ...

The selected check icon does not appear in the console log

Objective: Display preselected data from selected checkbox in console.log Issue: The preselected data is not appearing in the console log. When manually checked, the data shows up. What am I missing? About Me: I am a beginner in Angular. Thank ...

Parsing of the module failed due to an unexpected character appearing when trying to insert a TTF file into the stylesheet

As a newcomer to Angular, I recently completed the tutorial and am now working on my first app. While trying to add an OTF file, everything went smoothly. However, when I made a change to my app.component.css file and included this code snippet: @font-fa ...

generate a fresh array with matching keys

Here is an example array: subjectWithTopics = [ {subjectName:"maths", topicName : "topic1 of maths " }, {subjectName:"maths", topicName : "topic2 of maths " }, {subjectName:"English", topicName : &quo ...

Animation scaling on the iPhone seems to abruptly jump away once it finishes

Encountering an issue with animations that is causing unexpected behavior on physical iPhone devices but not in the simulators. The problem arises when the background zooms in and then the div suddenly jumps to the left after the animation completes, as sh ...