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

时间:2018-06-08 19:08:28

标签: angular rxjs observable

我目前在更新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 方法中尝试 console.log() PurchaseService#countSummaryPrice 的结果。它记录预期值,但未在 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);
  }

}

1 个答案:

答案 0 :(得分:0)

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

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