繁体   English   中英

角度:应用程序组件未检测到子组件的更改

[英]Angular: App Component not detecting change of Child Component

我正在构建一个购物车,除了网站首次加载时,其他一切工作正常,如果该人没有保存购物车,则他们必须在创建购物车之前单击添加到购物车。 问题是,我的app.component直到刷新页面后才意识到本地存储已更新。 我已经为此工作了3天,似乎无法弄清楚。 单击按钮后,我尝试刷新页面,但是这导致我的某些功能根本没有被调用。 我阅读了有关主题和行为变量的文章。 它似乎不符合我的需求。 据我了解,主题或行为变量需要订阅可观察对象,但是在这种情况下,我不需要订阅任何内容。 我只需要知道本地存储何时实时更新。 唯一相关的代码是app.component.ts中的代码,因为它是操纵购物车总计和计数的代码。 我添加了另一段代码,以防万一可能是个问题。 任何帮助将不胜感激,谢谢

app.component.ts

id: localStorage.getItem('cartId');

        if(this.id){
         this.dbList =  db.list('/shopping-carts/' + this.id).valueChanges().subscribe(items => {
            this.dbTotal = items[items.length - 1];
            this.dbCartCount = items.length - 2;
            console.log('total and cart count updated...');
          });

        } 

Clotheslist.component.ts

addToCart(product, price){
  let cartId = localStorage.getItem('cartId');

  if(!cartId){
    this.cartService.create().then(result => {
      localStorage.setItem('cartId', result.key);
      this.cartService.pushProductToCart(product, price);
      this.cartService.cartTotal(price);
    });
  //add product to cart
  } else {
  this.cartService.pushProductToCart(product, price);
  this.cartService.cartTotal(price);
  }
}

我会考虑将事件总线实现为Angular服务。 您将为此使用RxJs主题。

AppEventService:

@Injectable()
export class AppEventService {
  private eventBus: Subject<string> = new Subject<string>();
  public events: Observable<string> = this.eventBus.asObservable();

  constructor() {}

  publishEvent(eventName: string) {
    this.eventBus.next(eventName);
  }
}

Clothes-list.component.ts

addToCart(product, price){
  let cartId = localStorage.getItem('cartId');

  if(!cartId){
    this.cartService.create().then(result => {
      localStorage.setItem('cartId', result.key);
      this.cartService.pushProductToCart(product, price);
      this.cartService.cartTotal(price);
      //add product to cart
      this.eventsService.publishEvent('cart-updated');
    });
  } else {
  this.cartService.pushProductToCart(product, price);
  this.cartService.cartTotal(price);
  }
}

最后,在app.component.ts中:

@Component(...)
export class AppComponent {
   constructor(..., private eventsService: AppEventsService) {}

   ngOnInit() {
      this.eventsService.events
        .filter(eventName => eventName === 'cart-updated')
        .subscribe(this.handleCartChange.bind(this));
   }

   handleCartChange() {
      // execute your logic to update the cart total and item count here
   }
}

请注意,在提供观察者(订阅)以将上下文保留到组件类实例时,您可能必须使用JS绑定函数。

暂无
暂无

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

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