【发布时间】:2016-10-17 12:09:05
【问题描述】:
我正在使用 typescript 在 Angular 2 中构建一个基本的书店应用程序。 selectedBook(b: Books) 是我的 BookComponent 中的一个方法。
程序运行时,书籍列表显示在表格中,每本书 有它自己的“加入购物车”按钮。
点击添加到购物车按钮 调用
selectedBook(b: Books)方法并将所选书籍作为参数传递给该方法。- 进一步的方法应该将书添加到
cartArray变量(是数组 Books 模型),如果它是重复的书,则不应添加该书。 - 点击加入购物车时,作为重复的 bookQuantity
从书表视图中减少,它应该在
cartArray中增加(我 还没有为此编写代码作为 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存储到本地存储中。
图书组件:
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);
}
}
【问题讨论】:
标签: angular typescript angular2-template shopping-cart