首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >DOM元素中的值不会同时更新组件中的值

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

Stack Overflow用户
提问于 2018-06-09 03:08:28
回答 1查看 34关注 0票数 0

我目前在更新DOM中的值时遇到了一个问题。

header.component.ts

代码语言:javascript
复制
export class HeaderComponent implements OnInit {

  purchaseSummary = 0;

  constructor(private someService: SomeService) {
  }

  ngOnInit() {
    this.someService.summary.subscribe(
      observer => this.purchaseSummary = observer
    );
  }

}

header.html

代码语言:javascript
复制
<a>{{purchaseSummary}}</a>

some.service.ts

代码语言:javascript
复制
@Injectable()
export class SomeService {

  summary = new Subject<number>();

}

purchase.service.ts

代码语言:javascript
复制
@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

代码语言:javascript
复制
<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

代码语言:javascript
复制
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);
  }

}
EN

回答 1

Stack Overflow用户

发布于 2018-06-09 03:19:53

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

代码语言:javascript
复制
 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;
      }
    }
  }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50767032

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档