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



我正在构建一个购物车,一切都很好,除了当网站第一次加载时,如果用户没有保存购物车,他们必须在创建购物车之前单击"添加到购物车"。问题是,我的应用程序组件在刷新页面之前没有意识到本地存储会更新。我已经做了三天了,好像搞不明白。我试图在点击按钮后刷新页面,但这导致我的一些函数根本没有被调用。我读过关于受试者和行为变量的文章。它似乎与我所需要的不符。据我所知,主题或行为变量需要订阅可观察的,但在这种情况下我不需要订阅任何内容。我只需要知道本地存储何时实时更新。唯一相关的代码是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...');
});
} 

衣服清单组件.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);
}
}

衣服清单组件.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
}
}

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

最新更新