I’m using Angular 18 and I’m trying to work through a tutorial which is geared for a much older version.
Here is my Service class:
export class ProductsService
{
getProducts() : string[]
{
return ["Learning Angular","Pro TypeScript","ASP.NET"];
}
}
I’m trying to use this from my Component class by injecting it into the constructor. As such:
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 I’m getting is: NullInjectorError: NullInjectorError: No provider for ProductsService!
Now the documentation states that I need to add some code into app.module.ts:
But in this version of Angular, there is no such file as app.module.ts. So where am I supposed to define this dependency?
I found the answer while I was typing up the question. I searched for the term “providers” and I found it in app.config.ts. I modified this to add ProductsService to the array of providers.
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 solves the problem and the feature works!
However, this brings up a follow up question. Since this dependency is now scoped to the entire application, why should I not just make the getProducts method static and then call it from the type of ProductsService without requiring an instance of the class to be injected into the constructor?
2