慕碼人2483693
2023-04-20 10:01:31
所以我對(duì)此有點(diǎn)不以為然。希望你能給我道歉。我正在嘗試將多個(gè) Angular 元素(Web 組件)插入到 Prestashop 模塊,即 PHP。由于沒(méi)有一個(gè)包含許多模塊的 Angular 應(yīng)用程序,我無(wú)法使用商店將數(shù)據(jù)從一個(gè)元素發(fā)送到另一個(gè)元素。我想過(guò)創(chuàng)建一個(gè)負(fù)責(zé)創(chuàng)建 NGRX 商店的庫(kù),并將其保存到 window.store(例如),因此同一個(gè)商店可以被多個(gè)獨(dú)立的角度應(yīng)用程序使用。這里的問(wèn)題是我必須在許多 Angular 元素中調(diào)用庫(kù),所以我在構(gòu)造函數(shù)中注入了不同的存儲(chǔ)。我對(duì)嗎?例如:import { ActionReducer, ActionReducerFactory, ActionReducerMap, ActionReducerMap, ActionsSubject, ReducerManager, ReducerManagerDispatcher, StateObservable, Store,} from '@ngrx/store'import { Observable } from 'rxjs';const storeName = 'store'@Injectable({ providedIn: 'root'})export class StoreSyncService { store: any = null // option 1 constructor: // are we, when including the library in others angular apps, instantiating store over and over? constructor(private store: Store) { if (window[storeName]) { this.store = window[storeName] } else{ window[storeName] = this.store } } // option 2 constructor (please apologise me as I don't know how injection works very well). // Any link to clarify this is welcome constructor() { if (window[storeName]) { this.store = window[storeName] } else{ const stateObservable$: StateObservable = new Observable() const actionsObserver: ActionsSubject = new ActionsSubject() const dispatcher: ReducerManagerDispatcher = new ActionsSubject() const initialState = {} const reducers: ActionReducerMap<any, any> = {} const reducerFactory: ActionReducerFactory<any, any> = whatever const reducerManager: ReducerManager = new ReducerManager(dispatcher, initialState, reducers, reducerFactory) this.store = new Store(stateObservable$, actionsObserver, reducerManager) window[storeName] = this.store }所以回顧一下,如果我想在多個(gè)獨(dú)立的角度應(yīng)用程序之間共享狀態(tài),你會(huì)怎么做?我嘗試使用 localStorage,添加事件以將 NGRX 狀態(tài)與本地存儲(chǔ)中的數(shù)據(jù)同步,反之亦然,但有時(shí)會(huì)出現(xiàn)無(wú)限循環(huán),有時(shí)會(huì)出現(xiàn)數(shù)據(jù)不同步的邊緣情況。感謝您的幫助和理解
1 回答

繁星點(diǎn)點(diǎn)滴滴
TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超3個(gè)贊
所以現(xiàn)在,我找到了一種解決方法來(lái)避免商店的雙重實(shí)例化。使用條件注入器。
import { Injectable, Injector } from '@angular/core';
...
constructor(private injector : Injector) {
if (window[storeName]) {
this.store = window[storeName]
} else{
this.store = this.injector.get<Store>(Store);
window[storeName] = this.store
}
}
我還沒(méi)有測(cè)試它在獨(dú)立應(yīng)用程序之間共享數(shù)據(jù)。讓我們希望它有效。
隨時(shí)歡迎任何建議!
添加回答
舉報(bào)
0/150
提交
取消