在更新组件的同时,DOM元素中的值不会更新

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (57)

我目前在更新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()结果。它记录期望值,但不在header.html更改它

UPD: 忘记显示的位置: 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);
  }

}
提问于
用户回答回答于

假设您拥有的数据是“product”,请在删除产品时尝试此更新。

 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;
      }
    }
  }

扫码关注云+社区

领取腾讯云代金券