error NG2003: No suitable injection token for parameter 'id' of class

Viewed 7160

This is my service.ts file

import { Inject, Injectable } from '@angular/core';
import { inject } from '@angular/core/testing';

@Injectable({
  providedIn: 'root'
})


export class Product{
  constructor(
     public id: number,
     public title: string,
     public price: number,
     public rating: number,
     public description: string,
     public categories: string[]){}
}


export class ProductService {

  constructor() { }
  getProducts(): Product[] {
    return products.map(p =>new Product(p.id, p.title, p.price, p.rating, p.description, p.categories));
  }
}


const products =[
  {
    'id': 0,
    'title': 'First product',
    'price': 24.99,
    'rating': 4.3,
    'description': 'This is a short description for product Zeroth',
    'categories': ['electronics', 'hardware']
  }
]
Error: src/app/shared/product.service.ts:11:13 - error NG2003: No suitable injection token for parameter 'id' of class 'Product'.
  Consider using the @Inject decorator to specify an injection token.

11      public id: number,
               ~~

  src/app/shared/product.service.ts:11:17
    11      public id: number,
                       ~~~~~~
    This type is not supported as injection token.
1 Answers

This is supposed to be before the class ProductService, not Product :

@Injectable({
  providedIn: 'root'
})

Otherwise, Angular will try to inject the class Product and looks for injection tokens for the arguments of Product's constructor.

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[]){}
}
Related