を変更した後、私は私のangular2アプリで単純なコンポーネント持っているメソッドを呼び出します。私はAngular2 - モデルは
<div class="basket">
On your card: {{basketAmount()}}
</div>
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>#</th>
<th>Name</th>
<th>Desc</th>
<th>Price</th>
<th>Amount</th>
</tr>
</thead>
<tbody *ngFor="let product of products">
<tr>
<th scope="row">{{product.id}}</th>
<td>{{product.name}}</td>
<td>{{product.description}}</td>
<td>{{product.price}}</td>
<td>{{product.amount}}</td>
<button type="button" class="btn btn-success" (click)="addProductToCart(product)">Add to cart</button>
</tr>
</tbody>
</table>
とCartService
@Injectable()
export class CardService {
private cart: Product[] = [];
constructor() {
}
addProduct(product: Product) {
this.cart.push(product);
}
getTotalPrice() {
const totalPrice = this.cart.reduce((sum, cardItem) => {
return sum += cardItem.price, sum;
}, 0);
return totalPrice;
}
getNumberOfProducts() {
const totalAmount = this.card.reduce((sum, cardItem) => {
return sum += cardItem.amount, sum;
}, 0);
return totalAmount;
}
}
export interface Product {
id: number;
name: string;
description: string;
price: number;
amount: number;
}
:それに接続されている
@Component({
selector: 'app-product',
templateUrl: './product.component.html',
styleUrls: ['./product.component.css'],
providers: [ProductService, CardService]
})
export class ProductComponent implements OnInit {
private products;
constructor(private productService: ProductService, private cartService: CartService) {
}
ngOnInit() {
this.loadProducts();
}
loadProducts() {
this.productService.getProducts().subscribe(data => this.products = data);
}
addProductToCart(product: Product) {
this.cartService.addProduct(product);
}
basketAmount() {
this.cartService.getNumberOfProducts();
}
html
ファイルを何かをカートに追加して表示した後、カートのアイテム数を更新したい景色。私はクリックしてaddProductToCart
メソッドを呼び出してカートにアイテムを追加します。同時に、私はこのアイテムの数をbasketAmount()
で更新したいと考えています。これはCartService
で定義され、カートのアイテム数を返します。私はこのbasketAmount()
メソッドを何らかの形でトリガーすべきだと思っていますが、私は方法はわかりません。 良い方法でそれを行うには?
どこのサービスで 'getProducts()'のですか? – mercador
さて、私はそれが変だと思います。私はそれを変更します。手伝ってくれてありがとう。 – allocer