Unsuitable Injection Token Error for ‘id’ Parameter in Class: NG2003

To avoid issues with dependency injection in Angular, it’s important to ensure that the class is placed before the constructor, not after. If Angular is unable to find the necessary injection tokens for the constructor’s arguments, it won’t be able to inject the class properly. One solution to this problem is to add the @Injectable() decorator to the abstract base class, which became available with Angular 10. While this is a viable solution, it should be noted that it requires all constructor argument types to be resolvable by DI.


Solution:

The intended timing for

ProductService

is prior to the class, whereas

Product

should not be presented at that time.

@Injectable({
  providedIn: 'root'
})

If not, the class

Product

will be attempted to be injected by Angular. Furthermore, Angular will search for injection tokens to be utilized as arguments in the constructor of

Product

.

Try that :

@Injectable({
  providedIn: 'root'
})
export class ProductService {
  constructor() { }
  getProducts(): Product[] {
    return products.map(p =>new Product(p.id, p.title, p.price, p.rating, p.description, p.categories));
  }
}
export class Product{
  constructor(
     public id: number,
     public title: string,
     public price: number,
     public rating: number,
     public description: string,
     public categories: string[]){}
}

Frequently Asked Questions