我有两个组件,它们都使用同一个服务从localStorage中获取(get())和设置(set())项目。其中一个组件将项目添加到localStorage中。
import { Component, OnInit, Input } from '@angular/core';
import {Product} from '../product';
import { PRODUCTS } from '../mock-products';
import {CartService} from '../cart.service';
@Component({
selector: 'app-cart-item',
templateUrl: './cart-item.component.html',
styleUrls: ['./cart-item.component.css']
})
export class CartItemComponent implements OnInit {
@Input() cartItem: Product;
constructor(private cartService: CartService) { }
ngOnInit() { }
addToCart() { // adds item to localStorage
this.closeModal();
alert('item(s) successfully added to cart');
const cart = [];
const currentCart = this.cartService.get();
if (currentCart != null && currentCart.length > 0) {
for (let i = 0; i < currentCart.length; i++) {
cart.push(currentCart[i]);
}
}
cart.push(this.cartItem);
this.cartService.set(cart);
}
}
另一个组件从localStorage获取数据,并在表格中显示数据。
import { Component, OnInit, Input, ChangeDetectionStrategy } from
'@angular/core';
import { Product } from '../product'; // data types
import { PRODUCTS } from '../mock-products'; // database
import { CartService } from '../cart.service'; // service
@Component({
selector: 'app-checkout',
templateUrl: './checkout.component.html',
styleUrls: ['./checkout.component.css']
})
export class CheckoutComponent implements OnInit {
shoppingCart: Product[];
@Input() PRODUCTS: Product;
constructor(private cartService: CartService) { this.shoppingCart =
this.cartService.get(); }
ngOnInit() {}
checkOut() {
this.shoppingCart = this.cartService.get();
console.log(this.shoppingCart); // service is working, changes are
not being reflected in HTML
const span = document.getElementsByClassName('closeModal')[0];
const modal = document.getElementById('shoppingCart'); // pulls up
modal
modal.style.display = 'block';
}
在这个组件中,我可以通过运行 this.cartService.get() 来更改localStorage并实时查看更改。
deleteItem(id, shoppingCart) {
const newCart = [];
for (let i = 0; i < shoppingCart.length; i++) {
if (shoppingCart[i].id !== id) {
newCart.push(shoppingCart[i]);
}
}
this.cartService.set(newCart);
this.shoppingCart = this.cartService.get();
}
我已经在控制台中记录了信息,并将新项目设置为localStorage,但是表格不会更新新数据,除非刷新页面。
这是HTML表格,它使用*ngFor循环遍历“shoppingCart”并创建表格:
<table id="shoppingCartTable" >
<thead>
<th> Item </th>
<th> </th>
<th> </th>
<th> Price </th>
<th> Quantity </th>
<th> Total </th>
<th> Delete? </th>
<tr *ngFor="let cartItem of this.shoppingCart">
<td>{{cartItem.productName}}</td>
<td><img src={{cartItem.img}} /></td>
<td>{{cartItem.description}}</td>
<td>${{cartItem.price}}</td>
<td>{{cartItem.quantity}}</td>
<td>{{cartItem.price * cartItem.quantity}}</td>
<td><button><img src="./assets/icons/trashcan.png"
(click)="deleteItem(cartItem.id, shoppingCart)" /></button></td>
</tr>
<tr>
<button id="checkoutBtn"(click)="confirmCheckout()"> Checkout
</button>
</tr>
</thead>
<tbody id="tbodyCart"></tbody>
</table>
这是我的服务:
import { Injectable } from '@angular/core';
import { Product } from './product'; // data model
import { PRODUCTS } from './mock-products'; // database +
@Injectable()
export class CartService {
constructor() { }
set(shoppingCart: Product[]) {
localStorage.setItem('shoppingCart', JSON.stringify(shoppingCart));
}
get() {
return JSON.parse(localStorage.getItem('shoppingCart'));
}
}
我尝试使用默认的ChangeDetectionStrategy以及.OnPush,但都没有生效。我在stackOverflow上搜索了很久,也读了RxJs observables的相关内容,但是我并没有能够应用它们或者完全理解它们的工作方式,也不确定那是否是正确答案。我如何才能让我的视图层对另一个组件中localStorage的更改做出响应而不刷新?我是Angular的新手,希望得到一个Angular的解决方案,但任何指导都会有所帮助!