gpt4 book ai didi

angular - 错误 NG2003 : No suitable injection token for parameter 'id' of class

转载 作者:行者123 更新时间:2023-12-03 08:26:13 27 4
gpt4 key购买 nike

这是我的 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.

最佳答案

这应该位于类ProductService之前,而不是Product:

@Injectable({
providedIn: 'root'
})

否则,Angular 将尝试注入(inject)类 Product 并查找 Product 构造函数参数的注入(inject)标记。

尝试一下:

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

关于angular - 错误 NG2003 : No suitable injection token for parameter 'id' of class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66561496/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com