我在使用 Angular 和 Observable 时遇到了问题。
我有一个购物篮页面订阅了 BasketService 中数组的 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 = [];
}
有吗?
提示: - 当我重新加载 url 时,我有更新的商店(但我不能用路由器强制重新加载不知道为什么......) - 当我使用 ngOnInit 刷新时,我从 observable 中获取了旧值,即使我的数组是空的......
最佳答案
of
方法只是创建一个 Observable
,它会发出给定的参数然后完成。它不会跟踪您事后对参数所做的任何更改。
您可能想看看使用 Subject .一个主题同时充当观察者
和Observable
,允许您将数据推送给主题订阅者。在您的情况下,此数据将是您的商店数组。不是从文字值创建 Observables,而是从一个主题创建它们,您可以在值更改时更新该主题。
这是一个 super 简化的示例,用于实现我认为您正在寻找的单个数组:
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
方法将新数据推送到主题,以便订阅者能够通知。
关于angular - 如何更新使用 of(myArray) 创建的 RxJS Observable 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54787569/