Angular - 如何使用 rxjs 显示我的购物车项目的当前长度 [英] Angular - How show the current lenght of my cart items using rxjs
问题描述
我正在使用 Angular 9 做一个 SPA.我想要一个组件来显示我的购物车项目的当前长度,这样无需刷新页面就会自动显示我的购物车项目的长度(它将用于电子商务).
I am doing a SPA using Angular 9. I would like a component that shows the CURRENT length from my cart items and this way automatically without refresh the page shows the lenght from my cart items (it will be used on a ecommerce).
在我修改购物车项目的长度后,我模板上的属性没有显示当前长度.
The property on my template doesn't shows the current length after I have modified the length of my cart items.
如果我刷新页面,它会显示当前长度.
If I refresh the page, then it shows the current length.
public num_item:number;
ngOnInit(): void {
this.NumItemsCart().pipe(take(1)).subscribe( result =>
{this.num_item = result})
}
NumItemsCart():Observable<number>{
let cadena_items = '';
let array_temp = [];
let num_items=0;
cadena_items = localStorage.getItem('ecmm_list_shopcart');
array_temp= cadena_items.split(',')
num_items= array_temp.length -1
return of(num_items)
}
我的模板
<div *ngIf="(num_item) > 0">{{num_item}}</div>
请问,谁能告诉我正确的方法,并告诉我为什么我的方法不起作用?
Please, can someone show me the right way to do this and tell me why my method doesn´t works?
推荐答案
你可以使用异步管道和可选链
u can use the async pipe and the optional chain
<div *ngIf="(NumItemsCart|async)?.length > 0">{{(NumItemsCart|async)?.length}</div>
另一种方法是将 take(1)
更改为 takeUntil(destroy)
并在顶部添加类字段private destroy = new Subject()
,然后在 ngOnDestroy 中可以调用
another way is change the take(1)
to takeUntil(destroy)
and add class field at top private destroy = new Subject()
, then in ngOnDestroy you can call
this.destroy.next();
this.destroy.complete();
这篇关于Angular - 如何使用 rxjs 显示我的购物车项目的当前长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!