簡體   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. 特別是 3 個組件正在使用購物車組件服務。 他們是:

  1. navmenu 組件上的購物車圖標 - 它顯示購物車中商品的數量。
  2. 購物車摘要頁面 - 顯示購物車中的商品,並允許您使用數量組件(3)增加/減少商品的數量或將其從購物車中完全刪除。
  3. 數量 object。 這附加到產品頁面以及購物車中的行項目。 它可以增加或減少組件所在產品頁面的購物車中的商品數量。

購物車服務的公開方法是:

   //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> { ... }

由於該服務與 API 分離並分別注入到每個組件(產品組件、數量組件和導航菜單組件)中,因此單擊數量組件上的加號()或減號(-)按鈕正在更新數量 object,但navmenu 不會隨着數字的變化而更新。

例如,我的購物車組件上有這個,

<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.

在 .ts 文件中使用以下代碼

   ngOnInit() {
      this.getCart();
   }

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

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>

使用 .ts 文件中的此代碼,我的意圖是當我單擊產品上的 + 將其添加到購物車時,徽章葯丸中的商品數量應該增加。

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

我將 Observable 作為返回結果傳遞給我的所有購物車函數,以更新數量組件和產品組件中的局部變量 - 這導致它們正確更新和重新渲染,但更新永遠不會冒泡影響導航菜單,所以我可以在那里更新數量的唯一方法是刷新頁面。

為什么購物車計數,一個我訂閱的 observable,當我將商品添加到購物車時不會更新? 原諒我的無知,我是 Angular 的新手,並且仍在嘗試掌握它的所有功能。

提前致謝!

您的服務應該有一個購物車的行為主題,然后服務上的方法應該更新購物車中的數據。 您不應該從更新方法返回 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: [] });
}

在你的組件中

cart$ = this.cartSvc.cart$;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM