typescript - Angular CLI: 12.2.0 "ไม่มีการโอเวอร์โหลดใดที่ตรงกับการเรียกนี้"
ฉันกำลังพยายามสร้างรถเข็นสำหรับโปรเจกต์ Angular ฉันต้องการประกาศสินค้าว่าเป็น Product แต่ฉันพบข้อผิดพลาด: (ข้อความข้อผิดพลาดแสดงที่: "(product: Product) => { ..."
ไม่มีการเรียกใช้ที่ตรงกับการโอเวอร์โหลดนี้ โอเวอร์โหลดที่ 1 จากทั้งหมด 5, '(observer?: PartialObserver | undefined): Subscription', ให้ข้อผิดพลาดดังต่อไปนี้ อาร์กิวเมนต์ประเภท '(product: Product) => void' ไม่สามารถกำหนดค่าให้กับพารามิเตอร์ประเภท 'PartialObserver | undefined' ได้ คุณสมบัติ 'complete' หายไปในประเภท '(product: Product) => void' แต่จำเป็นในประเภท 'CompletionObserver' โอเวอร์โหลดที่ 2 จากทั้งหมด 5, '(next?: ((value: unknown) => void) | undefined, error?: ((error: any) => void) | undefined, complete?: (() => void) | undefined): Subscription', ให้ข้อผิดพลาดดังต่อไปนี้ อาร์กิวเมนต์ประเภท '(product: Product) => void' ไม่สามารถกำหนดค่าให้กับพารามิเตอร์ประเภท '(value: unknown) => void' ได้ ประเภทของพารามิเตอร์ 'product' และ 'value' ไม่เข้ากัน ประเภท 'unknown' ไม่สามารถกำหนดค่าให้กับประเภท 'Product' ได้ ts(2769)
ไฟล์ cart.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)
})
})
}
ฉันต้องการกดสินค้าที่เลือกจากอาร์เรย์ (เมื่อคลิกเพิ่มลงในรถเข็นบนหน้ารายการเมนู) ดังนั้นแทนที่จะมี "id: 1, productName: "string"..." ฉันจะมี productName: product.name และ productPrice: product.price ... นี่คือไฟล์ 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
}
}
และไฟล์ cart-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()
}
}
คำตอบ #1
ใน MessengerService เมื่อ Subject ถูกสร้างขึ้นด้วยตัวดำเนินการ new จำเป็นต้องเพิ่มพารามิเตอร์ชนิดทั่วไป ประโยค subject=new Subject() เดิมควรถูกเปลี่ยนเป็น subject=new Subject<Product>() ด้วยวิธีนี้เมื่อ Subject ถูกแปลงเป็น Observable ด้วย this.subject.asObservable() ชนิดที่ถูกส่งกลับจะเป็น Observable<Product> ด้วยวิธีนี้ เมธอด getMessage() จะมีชนิดการส่งค่ากลับที่ถูกต้องและเมธอด subscribe จะไม่แสดงข้อผิดพลาดใด ๆ