使用Angular和Observable时遇到问题。
我得到了一个购物篮页面,该页面订阅一个购物篮服务中一个包含数组的Observable数组,其中包含我的客户订单。当我单击验证按钮时,我清空了我的ordersArray,但是即使我的购物篮页面已订阅我的可观察对象,它也不会更新。
在我的BasketPage.ts中
ngOnInit() {
this.nourritureSubscription = this.panierService.nourritureStore.subscribe((data) => {
if(data.length === 0) {
this.isNourriturePanierEmpty = true;
} else {
this.nourriturePanier = data;
console.log(data)
this.isNourriturePanierEmpty = false;
}
});
this.menuSubscription = this.panierService.menuStore.subscribe((data) => {
if(data.length === 0) {
this.isMenuPanierEmpty = true;
} else {
this.menuPanier = data
console.log(data)
this.isMenuPanierEmpty = false;
}
})
}
consumePanier(){
let commandeSucess : boolean;
this.panierService.consumePanier()
this.commandeEnvoyee();
}
async commandeEnvoyee() {
const alert = await this.alertCtrl.create({
header: 'Commande envoyée !',
message: 'Votre commande a été approuvée et enregistrée',
buttons: [
{
text: 'Valider',
role: 'cancel',
cssClass: 'primary',
handler: () => {
this.ngOnInit();
}
}
]
});
await alert.present();
}
在我的BasketService.ts
nourritureArray: Nourriture[] = [];
menuArray: Menu[] = [];
nourritureStore = of(this.nourritureArray)
menuStore = of(this.menuArray)
consumePanier(){
let panierRef = [];
let user=JSON.parse(localStorage.getItem('user'));
panierRef.push({idUser: user.id})
Object.entries(this.nourritureArray).forEach(([key, value])=>{
panierRef.push({idNourriture: value.id, nameNourriture: value.name})
})
Object.entries(this.menuArray).forEach(([key, value])=>{
panierRef.push({idMenu: value.id, nameMenu: value.name})
})
let commande = JSON.parse(JSON.stringify(panierRef));
panierRef= [];
this.nourritureArray = [];
this.menuArray = [];
}
虽然吗?
提示: -当我重新加载网址时,我拥有更新的存储(但是我不能用路由器强制重新加载不知道为什么...) -当我使用ngOnInit刷新时,即使数组为空,我也从可观察的值中获取旧值。
答案 0 :(得分:1)
of
方法仅创建一个Observable
,它将发出给定的参数,然后完成。事实发生后,它将不会跟踪您对参数所做的任何更改。
您可能想看看使用Subject。主题既充当Observer
,又充当Observable
,使您可以将数据推送到主题订户。在您的情况下,此数据将是您的存储阵列。与其从文字值创建Observable,不如从值更改时可以更新的主题创建它们。
这是单个数组的超级简化示例,可以完成我认为您要寻找的内容:
export class BasketService {
// Create a new BehaviorSubject with an initial value of []
private Subject<Menu[]> menuSubject = new BehaviorSubject<>([]);
// Expose the menuSubject as an Observable (prevents consumers from pushing values)
Observable<Menu[]> menuStore = menuSubject.asObservable();
public addMenuItem(menuItem: Menu) {
// Get the current value of the menu store
const menus = this.menuSubject.getValue();
// Add the new menu
menus.push(menuItem);
// Push the updated menu to the subject
this.menuSubject.next(menus); // This is what notifies subscribers
}
public consumePanier() {
/// ... your business logic
// Update the value of the subject with an empty array
this.menuSubject.next([]); // This is what notifies subscribers
}
}
在此示例中要注意的重要一点是,每次更改数据时,都必须使用next
方法将新数据推送到主题,以便通知订户。