我正在使用typescript在Angular 2中构建一个基本的书店应用程序。 selectedBook(b: Books)
是 BookComponent 中的一种方法。
程序运行时,表格和每本书都会显示书籍清单 拥有"加入购物车"按钮
点击添加到购物车按钮 selectedBook(b: Books)
方法被称为&所选书籍作为参数传递给方法。
cartArray
变量(是...的数组)
书籍模型),如果它是重复的书,它不应该添加书。cartArray
中增加(I
没有为此编写代码作为idk从哪里开始)。books.model:
export interface Books {
id: number,
bookId: string,
bookName: string,
bookQuantity: number,
bookPrice: string,
bookAuthor: string,
bookPublished: string
}
在selectedBook(b: Books)
方法中工作(但它没有按我的预期工作):
selectedBook(b: Books)
时,会减少所选的图书数量并将其添加到购物车。bookId
的图书或
不,如果存在,它将布尔变量duplicateBook
设置为true
其他
false
。如果duplicateBook
为false
,则将图书添加到cartArray
。cartArray
存储到localstorage。BookComponent:
import {Component} from 'angular2/core';
import {Books} from '../models/books.model';
@Component({
selector: 'book',
templateUrl: `
<table class="table table-hover">
<tr>
<th>ID</th>
<th>Name</th>
<th>Quantity</th>
<th>Price</th>
<th>Author</th>
<th>Publisher</th>
<th>Actions</th>
</tr>
<tr *ngFor="#b of books">
<td><a>{{ b.bookId }}</a></td>
<td>{{ b.bookName }}</td>
<td>{{ b.bookQuantity }}</td>
<td>{{ b.bookPrice }}</td>
<td>{{ b.bookAuthor }}</td>
<td>{{ b.bookPublished }}</td>
<td>
<button type="button" class="btn btn-primary" *ngIf="b.bookQuantity > 0" (click)="selectedBook(b)">Add to cart</button>
<div *ngIf="b.bookQuantity < 1">Out of stock</div>
</td>
</tr>
</table>
`
})
export class BooksComponent {
books: Books[] = [
{ id: 1, bookId: '1', bookName: 'C', bookQuantity: 7, bookPrice: '2345', bookAuthor: 'fsdf', bookPublished: 'edsdf' },
{ id: 2, bookId: '2', bookName: 'Java', bookQuantity: 52, bookPrice: '3242', bookAuthor: 'sdfs', bookPublished: 'fghzxdffv' },
{ id: 3, bookId: '3', bookName: 'SQL', bookQuantity: 7, bookPrice: '5645', bookAuthor: 'dfghrty', bookPublished: 'ghjghj' }
];
cart: Books[] = [];
duplicateBook: boolean = false;
selectedBook(b: Books)
{
b.bookQuantity = b.bookQuantity - 1;
if (this.cart.length == 0) {
//b.bookQuantity = 1;
this.cart.push(b);
}
else {
for (let e of this.cart) {
console.log(e.bookId, "==", b.bookId);
if (e.bookId == b.bookId) {
console.log("Book is in cart");
this.duplicateBook = true;
break;
}
}
if (!this.duplicateBook) {
//increment previously added book quantity in cart by 1
this.cart.push(b);
}
}
localStorage.clear();
localStorage.setItem('cartItems', JSON.stringify(this.cart));
console.log("Cart contents are : ", this.cart);
}
}
答案 0 :(得分:0)
查看组件的所有代码会很有用。没有它很难说,但我相信模板中这一行的books
<tr *ngFor="#b of books">
指向书籍的副本,而不是指向服务中的实际对象。