请花点时间查看下面提到的所有三个文件。
cart.service.ts
export class CartService {
cart: Book[] = [];
constructor(private bookService: BooksService) { }
addToCart(book: Book) {
book.addedToCart = true;
this.bookService.updateCartValue(book);
this.cart.push(book);
}
get() {
return this.cart;
}
remove(book: Book) {
book.addedToCart = false;
this.bookService.updateCartValue(book);
this.cart = this.cart.filter((b) => b != book);
}
}
books.service.ts
export class BooksService {
bookArr: any;
constructor() { }
getBooks() {
this.bookArr = [
{
sno: 1,
name: 'A good book',
author: 'author 1',
image: 'https://m.media-amazon.com/images/I/814L+vq01mL._AC_UY327_FMwebp_QL65_.jpg',
amount: 400,
addedToCart: false
},
{
sno: 2,
name: 'A great book',
author: 'author 2',
image: 'https://m.media-amazon.com/images/I/41HrvsyKdBL._AC_UY327_FMwebp_QL65_.jpg',
amount: 500,
addedToCart: false
},
{
sno: 3,
name: 'A superb book',
author: 'author 3',
image: 'https://m.media-amazon.com/images/I/71B4h-dSVzL._AC_UY327_FMwebp_QL65_.jpg',
amount: 700,
addedToCart: false
},
{
sno: 4,
name: 'A terrific book',
author: 'author 4',
image: 'https://m.media-amazon.com/images/I/61Iz2yy2CKL._AC_UY327_FMwebp_QL65_.jpg',
amount: 1000,
addedToCart: false
},
{
sno: 5,
name: 'A mind-blowing book',
author: 'author 5',
image: 'https://m.media-amazon.com/images/I/71PpwN9ZsuL._AC_UY327_FMwebp_QL65_.jpg',
amount: 1400,
addedToCart: false
}
]
return this.bookArr;
}
updateCartValue(book: Book) {
console.log(book.addedToCart);
this.bookArr[book.sno -1].addedToCart = book.addedToCart;
console.log(this.bookArr[book.sno].addedToCart);
}
}
book.component.ts
export class BookComponent {
@Input() book: Book;
bookArr: Book[] = [];
constructor(private cartService: CartService, private bookService: BooksService) {
this.book = this.bookService.getBooks();
console.log(this.book);
}
addCart() {
this.cartService.addToCart(this.book);
console.log(this.book);
}
removeCart() {
this.cartService.remove(this.book);
}
}
如您所见,我正在尝试更新 books.service.ts 中
addedToCart
中的 bookArr
值。
问题是它没有更新值。
我正在尝试通过检索 addedToCart
值将
book.component.html中的“添加到购物车”按钮切换为“从购物车中删除”。由于该值未在全球范围内更新,因此我无法切换按钮。
我是初学者,我花了3个多小时试图解决这个问题。如果您知道答案,请付出额外的努力,尝试从概念上向我解释发生了什么。