简体   繁体   English

Angular 组件与后端服务之间的通信

[英]Communication between Angular components and backend services

I have a backend API written in C#, and my Angular App has a service layer of angular components between this API and the visual components. I have a backend API written in C#, and my Angular App has a service layer of angular components between this API and the visual components. 3 components in particular are using a shopping cart component service.特别是 3 个组件正在使用购物车组件服务。 They are:他们是:

  1. A shopping cart icon on a navmenu component - it shows a count of the number of items in the cart. navmenu 组件上的购物车图标 - 它显示购物车中商品的数量。
  2. A cart summary page - shows items in the cart and allows you to increase/decrease the qty of an item or delete it from the cart entirely using the quantity component (3).购物车摘要页面 - 显示购物车中的商品,并允许您使用数量组件(3)增加/减少商品的数量或将其从购物车中完全删除。
  3. Quantity object.数量 object。 This is attached to a product page as well as line items in the cart.这附加到产品页面以及购物车中的行项目。 It can increase or decrease the number of items in the cart for the product page the component sits on.它可以增加或减少组件所在产品页面的购物车中的商品数量。

The exposed methods for the cart service are:购物车服务的公开方法是:

   //Add item to cart or increment qty of item by 1
   addToCart(product: Product): Observable<ShoppingCart> { ... }

   //Decrement qty of item by 1 or delete if qty = 0
   removeFromCart(product: Product): Observable<ShoppingCart>{.... }

   //Get all items in cart
   getCartItems(): Observable<ShoppingCart>{ ...}

   // Delete all items in cart
   async clearCart(): Promise<Observable<ShoppingCart>>{ ... }

   // Delete entire cart
   async removeCart(): Promise<void> { ... }

Because the service is detached from the API and injected into each of the components separately (product component, quantity component and navmenu component), clicking the plus() or minus (-) button on the quantity component is updating the quantity object, but the navmenu is not getting updated as the numbers change.由于该服务与 API 分离并分别注入到每个组件(产品组件、数量组件和导航菜单组件)中,因此单击数量组件上的加号()或减号(-)按钮正在更新数量 object,但navmenu 不会随着数字的变化而更新。

For instance, I have this on my cart component,例如,我的购物车组件上有这个,

<ng-container *ngIf="cart$ | async as cart">
  <div class="card">
    <div class="card-body">
      <h6 class="card-subtitle card-mb-4 card-tb-4 text-muted">
         You have {{cart.itemCount}} items in your cart.

with the following code in the.ts file在 .ts 文件中使用以下代码

   ngOnInit() {
      this.getCart();
   }

   async getCart() {
      this.cart$ = await this.cartSvc.getCartItems();
   }

The navmenu component has this code in the page navmenu 组件在页面中有这段代码

        <li class="nav-item">
          <a class="nav-link" routerLink="/cart">
            <span class='fa fa-shopping-cart'></span>
            <span *ngIf="cart$ | async as cart">
            <span class="badge badge-warning badge-pill" *ngIf="cart.itemCount">{{ cart.itemCount }}</span>
            </span>
          </a>
        </li>

with this code in the.ts file, my intent being that the number of items should increase in the badge-pill when I clicked the + on a product to add it to the cart.使用 .ts 文件中的此代码,我的意图是当我单击产品上的 + 将其添加到购物车时,徽章药丸中的商品数量应该增加。

   async ngOnInit() {
      // No need to unsubscribe as only 1 instance in DOM for lifetime of application
      this.cart$ = this.cartSvc.getCartItems();
   }

I passed Observable as return results in all my cart functions to update the local variables in the quantity component and the product component - this is causing them to update and re-render properly, but the update never bubbles up to affect the navmenu, so the only way I can get the quantity there to update is to refresh the page.我将 Observable 作为返回结果传递给我的所有购物车函数,以更新数量组件和产品组件中的局部变量 - 这导致它们正确更新和重新渲染,但更新永远不会冒泡影响导航菜单,所以我可以在那里更新数量的唯一方法是刷新页面。

Why does the cart count, an observable I am subscribing to, not update when I add items to the cart?为什么购物车计数,一个我订阅的 observable,当我将商品添加到购物车时不会更新? Forgive my ignorance, I am new to Angular and still trying to get a handle on all its features.原谅我的无知,我是 Angular 的新手,并且仍在尝试掌握它的所有功能。

Thanks in advance!提前致谢!

Your service should have a behavior subject for the cart and then the methods on the service should be updating the data in the cart.您的服务应该有一个购物车的行为主题,然后服务上的方法应该更新购物车中的数据。 You should not be returning observables from the update methods.您不应该从更新方法返回 observables。

cart$ = new BehaviorSubject<ShoppingCart>({ products: [] });

addToCart(product: Product) {
  const cart = this.cart$.value;
  this.cart$.next({ ...cart, products: [ ...cart.products, product] });
}

removeFromCart(product: Product) {
  const cart = this.cart$.value;
  this.cart$.next({ ...cart, products: cart.products.filter(p => p.id !== product.id) });
}

clearCart() {
  const cart = this.cart$.value;
  this.cart$.next({ ...cart, products: [] });
}

and in your component在你的组件中

cart$ = this.cartSvc.cart$;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM