I am currently facing difficulties with properly injecting my service class into the constructor of my component in Angular 18

I've encountered an issue while working on a tutorial in Angular 18 that seems to be targeted towards an older version of the framework.

Below is my Service class:

export class ProductsService
{ 
    getProducts() : string[] 
    { 
        return ["Learning Angular","Pro TypeScript","ASP.NET"]; 
    } 
}

I am attempting to utilize this service in my Component class by injecting it into the constructor as shown below:

import { CommonModule } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { ProductsService } from './products.service';

@Component({
  selector: 'app-products',
  standalone: true,
  templateUrl: './products.component.html',
  styleUrl: './products.component.css',
  imports: [CommonModule]
})
export class ProductsComponent implements OnInit {

  products: string[] = [];

  constructor(ps: ProductsService)
  { 
    this.products = ps.getProducts(); 
  }

  ngOnInit(): void
  {
  }
}

The error message I'm facing is: NullInjectorError: NullInjectorError: No provider for ProductsService!

The documentation suggests adding some code into app.module.ts:

https://i.sstatic.net/8MI8GcbT.png

However, since there is no app.module.ts file in this version of Angular, I am unsure where to define this dependency. Any help would be appreciated.

Answer №1

In the process of typing out my question, I stumbled upon the solution. After searching for the term "providers", I discovered it within app.config.ts. To resolve the issue, I included ProductsService in the providers array.

import { ApplicationConfig, provideZoneChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { ProductsService } from './products/products.service';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers:
    [provideZoneChangeDetection({ eventCoalescing: true }), 
      provideRouter(routes), 
      ProductsService
    ]
};

This fix successfully resolved the problem and now the feature is functioning as expected!

Another approach would be to directly incorporate DI support within the service definition itself: (Credit goes to Matthieu Riegler for suggesting this option in the comment section).

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})

export class ProductsService
{ 
    getProducts() : string[] 
    { 
        return ["Learning Angular","Pro TypeScript","ASP.NET"]; 
    } 
}

However, this does raise a new question. Since this dependency is now application-wide, why not make the getProducts method static and access it directly from the type of ProductsService instead of needing an instance of the class to be injected into the constructor?

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

Trigger the "onChange" event when the input element is modified by JavaScript within a popup window

On my webpage, I have a form element and a popup window (which is opened using window.open). Both the form element and the popup window utilize jQuery. The JavaScript in the popup window has the ability to alter the form element on the main page successf ...

Using MongoMapper with Rails to efficiently render arrays in views

In my Rails application, I have a controller that retrieves data from MongoDB. The specific field I need is actually an array, and I want to display it in an erb view. Currently, my workaround involves setting the JavaScript variable directly in the view ...

Trouble with feedback form not showing up

I've been working on creating an ajax feedback form, but I'm facing difficulties in getting it to show up properly. The feedback image appears, but clicking on it doesn't trigger any action. Here's my Form: <div id="feedback"> ...

Is it possible to utilize MongooseArray.prototype.pull() in typescript?

A problem has arisen in Typescript at this specific line of code: user.posts.pull(postId); An error message I'm encountering states: Property 'pull' does not exist on type 'PostDoc[]' The issue seems to be related to the fac ...

The module 'NgAutoCompleteModule' was declared unexpectedly by the 'AppModule'. To fix this issue, make sure to add a @Pipe/@Directive/@Component annotation

Currently, I am attempting to integrate an autocomplete feature into my Angular 2/4+ project. Despite trying various libraries, none of them seem to be working correctly. Each one presents me with a similar error message: Unexpected module 'NgAutoCom ...

How to design a dictionary schema using Mongoose

I have been attempting to save a dictionary of objects using Mongoose. Upon realizing that the change detection for saving is lost when using the Mixed type, I am looking for a way to create a schema that does not rely on the Mixed type. While there are m ...

Setting up a Bootstrap tokenfield for usage with a textarea

I was attempting to set up a tokenfield on a textarea with increased height, but it is showing up as a single-line textbox. How can I modify the tokenfield to function properly with a textarea? <textarea name="f1_email" placeholder="Enter Friends' ...

Create a tuple type by mapping an object with generics

I have a specified object: config: { someKey: someString } My goal is to generate a tuple type based on that configuration. Here is an example: function createRouter< T extends Record<string, string> >(config: T) { type Router = { // ...

What is the reason for the removal of the `?` decorator in this mapped type? Are there alternative methods to achieve a similar outcome without eliminating it

Challenge In the process of creating a mapped type that excludes properties of type Function, we encountered an issue. Our current method not only eliminates functions but also strips away the optional decorator (?) from the mapped properties. Scenario ...

Fixing Typescript assignment error: "Error parsing module"

Trying to assign an object to the variable initialState, where the type of selectedActivity is Activity | undefined. After using the Nullish Coalescing operator (??), the type of emptyActivity becomes Activity. However, upon execution of this line, an err ...

Error encountered: ERESOLVE issue occurred while attempting to resolve dependencies during npm install

After attempting to run 'npm install' to download the dependencies from a cloned repository, an error appeared on the terminal. The operating system being used is Windows 10. npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: ...

"Discover the seamless process of uploading images in Angular 7 directly from the backend

I'm facing an issue where I can upload images using Postman, but it's not working for me in Angular. Can someone please provide a solution? Error: Cannot read originalname of undefined in Node.js, but it works with Postman! //backend var exp ...

Navigating through Observables in Angular Applications

In my Angular application, I am utilizing the RxJs library to retrieve data from a backend API server. The method for this call is shown below: allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] { const self = this; const ...

RequiredFieldValidator is unable to detect any text that has been assigned through JavaScript

On my ASP.NET page, I have a telerik RadTextBox connected to a RequiredFieldValidator. An issue arises when I set a value to the RadTextBox using javascript like this: document.getElementById('<%= mytextbox.ClientID %>').value = myvalu ...

Error when using jQuery AJAX to parse JSONP callback

Take a look at this code snippet: $(function () { $.ajax({ type: "GET", url: "http://mosaicco.force.com/siteforce/activeretailaccounts", dataType: "jsonp", crossDomain: true, jsonp: "callback", error: f ...

Express JS is experiencing difficulties with the functionality of the iframe

When I'm using iframe in HTML, it works perfectly fine: <iframe src="main.html" height="100px"></iframe> But when I use Iframe in Express, it shows an error: <iframe src="main.html" height="100px&qu ...

"Trying to refresh your chart.js chart with updated data?”

Greetings! I have implemented a chart using chart.js and here is the corresponding code: let myChart = document.getElementById('myChart').getContext('2d'); let newChart = new Chart(myChart, { type: 'line', data: { labels: ...

What is the process for generating an Electronic Program Guide for television?

Welcome to the forum! I'm a front-end developer at a company for 6 months now, currently working on a TV app. It's my first experience in this field and I'm facing some challenges, particularly with creating an epg for the app. Unfortunately ...

Error loading ngsw-worker.js in Angular 7

Issue An app that utilizes a Service Worker is experiencing problems. The app was recently upgraded from Angular 6.1 to version 7. Upon uploading the updated files to the server, an error message is displayed: https://i.sstatic.net/B7uPf.png Error Det ...

What are the best methods for embedding HTML code from one page into another within an HTML document?

My current challenge involves working on a webpage that contains an iframe with a specific source. I am now tasked with creating an offline version of the same page, without having multiple pages. Essentially, I need to find a way to store and access the ...