Angular 角度视图不更新数据

Angular 角度视图不更新数据,angular,Angular,我不熟悉angular编程,所以如果我的问题没有很好的结构化,请容忍我。我正在尝试创建一个简单的食品订购应用程序,因此我有一个服务,同时从json文件中获取模拟数据,它还有一些处理数据的方法 import { Injectable, FactoryProvider } from '@angular/core'; import { groupBy, remove, find } from "lodash"; import { foodItems } from "./food-items.const

我不熟悉angular编程,所以如果我的问题没有很好的结构化,请容忍我。我正在尝试创建一个简单的食品订购应用程序,因此我有一个服务,同时从json文件中获取模拟数据,它还有一些处理数据的方法

import { Injectable, FactoryProvider } from '@angular/core';
import { groupBy, remove, find } from "lodash";
import { foodItems } from "./food-items.constants"
import { Router } from '@angular/router';
@Injectable({
  providedIn: 'root'
})
export class DataService {
      private foodz = foodItems;
      private cart = [];
      private CartObject = {};
      private totalAmount: number = 0;
      constructor(private router: Router) {

      }
      getTotal() {
        return this.totalAmount;
      }
      getCart() {
        return this.cart;
      }

      getFoodItems() {
        let items = groupBy(this.foodz, function (food) {
          return food.cuisine;
        });
        return items;
      }
      addItemToCart(item) {
        let cartItem = find(this.cart, function (cartObject) {
          if (cartObject.itemName === item.itemName) {
            cartObject.quantity++;
            cartObject.Amount = cartObject.quantity * item.pricePerUnit;
            return true;
          }
        });
        if (cartItem) {
          this.totalAmount += Number(item.pricePerUnit);
          alert(this.totalAmount);

        }
        if (!cartItem) {
          this.cart.push({
            'itemName': item.itemName,
            'quantity': 1,
            'Amount': item.pricePerUnit
          });
          this.totalAmount += item.pricePerUnit;
          alert(this.totalAmount);

        }
        return true;
      }
      removeItemFromCart(item) {
        let cartItem = find(this.cart, (cartObject) => {

          if (cartObject.itemName === item.itemName) {
            if (cartObject.quantity == 1) {
              this.totalAmount -= item.pricePerUnit;
              alert(this.totalAmount);
              remove(this.cart, function (cObject) {
                if (cObject.itemName == item.itemName) {
                  return true;
                }
              });
            }
            else {
              cartObject.quantity--;
              cartObject.Amount = cartObject.quantity * item.pricePerUnit;
              this.totalAmount -= item.pricePerUnit;
              alert(this.totalAmount);
              return true;
            }
          }
        });
        if (!cartItem) {

        }
        return true;
      }
}
接下来,我有一个组件,它有一个通过DI和用户操作的服务实例,我试图在购物车中添加和删除食物。 问题 虽然我的购物车正在正确更新,但在我从购物车添加或删除项目时,
total
变量不会立即更新。 这是我的component.ts文件内容

      import { Component, OnInit } from '@angular/core';
  import { DataService } from '../data.service';

  @Component({
    selector: 'app-add-card',
    templateUrl: './add-card.component.html',
    styleUrls: ['./add-card.component.css']
  })
  export class AddCardComponent implements OnInit {
    private cart = [];
    private total: number;

    constructor(private foodService: DataService) {

    }

    ngOnInit() {
      this.cart = this.foodService.getCart();
      this.total = this.foodService.getTotal();

    }
  }
这是我的view component.html文件,用于显示购物车摘要

<div class="menu text-center" > <br>
 <h1><span>{{ total | currency: "INR" }}</span></h1 > <br>
</div>
< br >

<div class="menu" style = "margin-bottom: 30px" >
  <div class="heading text-center" >
    <span>Order Details < /span>
  </div>


  < div class="item" * ngFor="let item of cart" >
        <span style="width:50%;display:inline-block" > {{ item.itemName }}</span>
        <span style = "width:20%;display:inline-block" > Qua.{ { item.quantity } } </span>
         <span > {{ item.Amount | currency: "INR" }} { { cart.total } } </span>
    </div>
</div>

{{总|货币:印度卢比}}

订单详情
{{item.itemName} 质量{{item.quantity} {{item.Amount}货币:{cart.total}}
它不会更新,因为您没有监听服务中的
总计
值中所做的更改

为服务中的总价值添加一个主题,组件可以订阅主题中的更改并相应地更新其变量

在您的服务中,您可以选择:

public totalObs = new Subject()
totalSub: Subscription
ngOnInit() {
   this.cart = this.foodService.getCart();
   this.totalSub = this.foodService.totalObs.subscribe((total) => {this.total = total}); 
}

ngOnDestroy() {
    if (this.totalSub) {
        this.totalSub.unsubscribe()
    }
}
无论您在何处更新服务中的总计,请执行以下操作:

this.totalObs.next(this.total)
在您的组件中,有如下内容:

public totalObs = new Subject()
totalSub: Subscription
ngOnInit() {
   this.cart = this.foodService.getCart();
   this.totalSub = this.foodService.totalObs.subscribe((total) => {this.total = total}); 
}

ngOnDestroy() {
    if (this.totalSub) {
        this.totalSub.unsubscribe()
    }
}

你能用现场演示创建一个stackblitz,这样我们就可以编辑它了吗?好的,我会的。可能是重复的谢谢你的解决方案,我会试试这个,然后给你回复。只是一个补充问题:如何更新我的购物车,然后在飞行中,一旦我添加或删除购物车的项目。我没有为此写任何东西,但它似乎在我不写任何东西的情况下更新。@GaganDeep请显示您为更新购物车而编写的组件代码(HTMl和ts),该组件只是调用服务方法,如
this.foodService.addItemToCart(item)就是这样。我从html向它发送项目。它会将其添加到购物车中,并且我的视图会立即更新。@GaganDeep
cart
是一个数组,它的引用在组件和服务之间共享,只要您在浏览器上执行操作(单击“添加/删除”),就会运行更改检测并检查现有数据。对于
total
也应如此,但
total
是一种基本类型,其引用不在组件和服务之间共享,因此服务中所做的更改不会影响组件中的更改。确定。谢谢@xyz,我会在我有笔记本电脑的时候试试这个,然后再回复你。谢谢你的努力。