我目前在更新DOM中的值时遇到了一个问题。
header.component.ts
export class HeaderComponent implements OnInit {
purchaseSummary = 0;
constructor(private someService: SomeService) {
}
ngOnInit() {
this.someService.summary.subscribe(
observer => this.purchaseSummary = observer
);
}
}
header.html
<a>{{purchaseSummary}}</a>
some.service.ts
@Injectable()
export class SomeService {
summary = new Subject<number>();
}
purchase.service.ts
@Injectable()
export class PurchaseService {
products: { name: string, price: number }[] = [];
constructor(private someService: SomeService) {
}
addProduct(product: { name: string, price: number }) {
this.products.push(product);
this.someService.summary.next(this.countSummaryPrice());
}
deleteProduct(id: number) {
this.products.splice(id, 1);
this.someService.summary.next(this.countSummaryPrice());
}
countSummaryPrice() {
let sum = 0;
for (let i = 0; i < this.products.length; i++) {
sum += this.products[i].price;
}
return sum;
}
}
当我在另一个DOM PurchaseService#addProduct中执行时,它通常会增加header.html.中的值当我试图通过执行PurchaseService#deleteProduct来删除产品时,它会从数组中删除项,但header.html中的值没有改变。此外,我还尝试在PurchaseService#deleteProduct方法中对PurchaseService#countSummaryPrice的结果进行console.log()。It记录期望值,但不在header.html中更改它
更新:忘记了它显示的地方:purchase.component.html
<table>
<thead>
<tr>
<th >#</th>
<th >Product</th>
<th >Price</th>
<th >&</th>
</tr>
</thead>
<tbody *ngFor="let product of products; let i = index">
<th scope="row">{{i+1}}</th>
<td>{{product.name}}</td>
<td>{{product.price}}</td>
<td><button class="btn btn-danger" (click)="onDelete(i)">X</button></td>
</tbody>
</table>
和purchase.component.ts
export class PurchaseComponent implements OnInit {
products: { name: string, price: number }[];
constructor(private purchaseService: PurchaseService) { }
ngOnInit() {
this.products = this.purchaseService.products;
}
onDelete(id: number) {
this.purchaseService.deleteProduct(id);
}
}
发布于 2018-06-09 03:19:53
假设您拥有的数据是“products”,请尝试在删除产品时进行更新。
deleteProduct(id: number) {
this.removeProduct(productId);
this.someService.summary.next(this.countSummaryPrice());
}
removeProduct(productId) {
for (let i = 0; i < this.products.length; i++) {
if (this.products[i].id === productId) {
this.products.splice(i, 1);
break;
}
}
}
https://stackoverflow.com/questions/50767032
复制相似问题