【发布时间】:2021-08-23 19:13:54
【问题描述】:
我正在尝试为 Angular 项目创建一个购物车。我想将产品声明为产品,但我遇到了错误: (错误消息显示在:“(产品:产品)=> { ...”
没有重载匹配这个调用。 Overload 1 of 5, '(observer?: PartialObserver | undefined): Subscription',给出了以下错误。 '(product: Product) => void' 类型的参数不可分配给'PartialObserver |不明确的'。 “(产品:产品)=> void”类型中缺少属性“完整”,但在“CompletionObserver”类型中是必需的。 重载 2 of 5, '(next?: ((value: unknown) => void) | undefined, error?: ((error: any) => void) | undefined, complete?: (() => void) | undefined): Subscription',给出了以下错误。 “(产品:产品)=> void”类型的参数不可分配给“(值:未知)=> void”类型的参数。 参数“product”和“value”的类型不兼容。 类型“未知”不可分配给类型“产品”。ts(2769)
我的购物车.components.ts:
ngOnInit() {
this.message.getMessage().subscribe((product: Product) => {
this.cartItems.push({
id: 1,
productName: "string",
qty: 1,
price: 1
})
this.cartItems.forEach(item => {
this.cartTotal += (item.qty * item.price)
})
})
}
我想推送从数组中选择的产品(单击菜单页面上的添加到购物车时)。因此,我将使用 productName: product.name 和 productPrice: product.price ... 而不是“id: 1, productName: "string"...” 这是我的 product.services.ts:
export class ProductService {
products: Product[] = [
new Product(1, 'Product 1', 'P1 description', 100, 'image1.png'),
new Product(2, 'Product 2', 'P2 description', 300, 'image2.jpg'),
new Product(3, 'Product 3', 'P3 description', 50, 'image3.png'),
new Product(4, 'Product 4', 'P4 description', 20, 'image4.jpg'),
new Product(5, 'Product 5', 'P5 description', 400, 'image5.jpg'),
new Product(6, 'Product 6', 'P6 description', 40, 'image6.jpg'),
]
constructor() { }
getProducts(): Product[] {
return this.products
}
}
还有我的购物车-item.components.ts:
export class CartItemComponent implements OnInit {
@Input() cartItem: any
constructor() { }
ngOnInit() {
}
}
信使服务:
export class MessengerService {
subject = new Subject()
constructor() { }
sendMessage(product: Product) {
this.subject.next(product)
}
getMessage() {
return this.subject.asObservable()
}
}
【问题讨论】:
-
this.message.getMessage()返回什么?很可能它不是 rxjs Observable,这就是subscribe抛出错误的原因。 -
这是我的 messages.service.ts 文件:
export class MessengerService { subject = new Subject() constructor() { } sendMessage(product: Product) { this.subject.next(product) } getMessage() { return this.subject.asObservable() } } -
嗯..
getMessage()的返回值好像没问题,哪一行抛出No overload matches this call错误? -
在我的购物车.component.ts:i.imgur.com/SadOOSd.png
-
您能否尝试在
MessengerService中添加Product类型作为Subject实例化的通用参数?我的意思是subject = new Subject<Product>()。
标签: angular typescript