错误 NG2003:class 的参数 'id' 没有合适的注入令牌

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

这是我的 service.ts 文件

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.

这应该在 class ProductService 之前,而不是 Product :

@Injectable({
  providedIn: 'root'
})

否则,Angular 将尝试注入 class Product 并为 Product 的构造函数的参数寻找注入标记。

试试看:

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