我正在使用行為主題在 Angular 應用程式中管理我的狀態。我正在使用兩種服務。一種使用 Web 套接字執行發送和獲取請求,另一種將資料存盤在 observable 中。檢索到資料后,我將資料傳遞給行為主體。我這里有問題。一切正常,除了當我洗掉專案并按后退按鈕時。在此程序中,我的一些資料丟失了。我不知道為什么會這樣。這是我的代碼:
cart.store.ts // 用于管理狀態
private cartItems$ = new BehaviorSubject<Product[]>(null);
private items: Product[] = [];
setCart(cartItems: Product[]) {
this.cartItems$.next(cartItems);
}
setSingleItem(item: Product) {
this.items.push(item);
this.cartItems$.next(this.items);
}
deleteCart(item: Product) {
this.cartItems$.subscribe((res) => {
let index;
for (let i = 0; i < res.length; i ) {
if (item.upc === res[i].upc) {
index = i;
}
}
res.splice(index, 1);
});
}
car.component.ts //呼叫cart service并獲取資料
getCartItems() {
if (!this.cartItems?.length) {
const payload = this.localStorageService.getData(LOCAL_STORAGE_KEY.PHONE);
this.cartService.getCart(payload).then((res) => {
//after fetching storing the data
this.cartStore.setCart(res);
for (let x = 0; x < res.length; x ) {
this.totalPrice = this.totalPrice res[x].price;
}
this.cartItems$ = this.cartStore.getCart(); //using async pipe to display in template
});
}
}
car.service.ts //用于獲取和洗掉資料
getCart(payload): Promise<any> {
this.socketService.sendMessage(AUTH_EVENTS.ON_DEVICE_CONNECT, payload);
const serverRes = (async () => {
try {
const data = await this.socketService.receivedJustSingleValue(
CART_EVENTS.GET_CART_ITEMS,
);
if (data) {
return data;
} else {
throw new Error('error');
}
} catch (error) {
return error;
}
})();
return serverRes;
}
//remove cart works the same way
當我洗掉一個專案并按下后退按鈕時,我的資料就會丟失。誰能告訴我出了什么問題?
uj5u.com熱心網友回復:
問題出在deleteCart函式上。你訂閱了 observable 但永遠不會取消訂閱。因此,每次您呼叫 時next(), ThedeleteCart都會再次運行并洗掉一個專案。
您可以使用BehaviorSubject.value來獲取當前專案。結果應該是這樣的:
private cartItems$ = new BehaviorSubject<Product[]>(null);
// private items: Product[] = [];
setCart(cartItems: Product[]) {
this.cartItems$.next(cartItems);
}
setSingleItem(item: Product) {
this.cartItems$.next([...this.cartItems$.value, item]);
}
deleteCart(item: Product) {
const items = this.cartItems$.value;
let index;
for (let i = 0; i < items.length; i ) {
if (item.upc === items[i].upc) {
index = i;
}
}
items.splice(index, 1);
this.cartItems$.next(items);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/343780.html
