メインコンポーネントで、データの初期化を開始します。
_store.dispatch(_statusActions.initialize());
これにより、すべての初期化アクションがトリガーされます。
@Effect()
loading$ = this.actions$
.ofType(StatusActions.INITIALIZING)
.mergeMap(() => Observable.from([
this._characterActions.initCharacters(),
this._vehicleActions.initVehicles()
]))
データがストアにロードされた後、すべてのストアエンティティに対して成功アクションがトリガーされます。
車両の場合:
@Effect()
loadVehicles$ = this.actions$
.ofType(VehicleActions.INIT_VEHICLES)
.switchMap(() => this._vehicleService.getVehicles()
.map((vehicles: Vehicle[]) => this._vehicleActions.initVehiclesSuccess(vehicles))
.catch(err => Observable.of(this._statusActions.dataLoadingError('vehicles')))
);
そしてキャラクターの場合:
@Effect()
loadVehicles$ = this.actions$
.ofType(CharacterActions.INIT_CHARACTERS)
.switchMap(() => this._characterService.getCharacters())
.map((characters: Character[]) =>
this._characterActions.initCharactersSucess(characters))
そして最後に、すべての* _DATA_SUCCESSアクションがトリガーされた後、INITIALIZEDアクションをトリガーして、ストレージにREADYフラグを設定する必要があります。
export const initReducer = (state: boolean = false, action: Action): boolean => {
switch (action.type){
case StatusActions.INITIALIZING:
return false;
case StatusActions.INITIALIZED:
console.log('App initialized...');
return true;
default:
return state;
}
私の質問-それをどのように実行するのですか?すべての成功アクションがトリガーされたことを知る方法は?
UPD
Snks mtx、私はあなたの最初のそしてより速いアドワイズに従いました。
余分な質問は申し訳ありませんが、私は本当に次のステップを実行するための素晴らしい理由を探して立ち往生しました。INITIALIZEDアクションが実行されるまでこのサブスクリプション(コンポーネント内)を保持する方法(if(vehicles.length> 0)でこのひどい松葉杖を削除する必要があります):
constructor(
...
) {
this.vehicles$ = _store.select(s => s.vehicles);
this.initialized$ = _store.select(s => s.initilized);
}
ngOnInit() {
let id = this._route.snapshot.params.id ? this._route.snapshot.params.id :
null;
this.sub = this.vehicles$.subscribe(vehicles => {
if (vehicles.length > 0){
if(id){
this.vehicle = vehicles.find(item => item.id === Number(id))
} else {
this.vehicle = new Vehicle(vehicles[vehicles.length-1].id+1, '');
}
this.viewReady = true;
}
})
}
ngOnDestroy(){
this.sub && this.sub.unsubscribe();
}
subscribe()の前にskipUntil()を挿入しようとしましたが、このコンポーネントを別のコンポーネントから開くときに問題が発生します(すべてのデータが既にロードされている場合)。この場合、サブスクライブコールバックはもう起動できません!理由がわからない...
...
private initDone$ = new Subject<boolean>();
...
this.initialized$.subscribe((init: Init) => {
if(init.app)
this.initDone$.next(true);
})
this.sub = this.vehicles$.skipUntil(this.initDone$).subscribe(vehicles => {
if(id)
this.vehicle = vehicles.find(item => item.id === Number(id))
else
this.vehicle = new Vehicle(vehicles[vehicles.length-1].id+1, '');
this.viewReady = true;
});
}
私の問題を再現するには、リストにある車両の1つを押すだけです。サブスクライブコールバックが起動しません。次に、F5->車両の積載を押します。設計どおりにコールバックが発生しました。
完全なソースコードはここにあります:GitHub、GitHubPagesで実行されている最後のバージョン
これを行うには2つの方法が考えられます(他の方法があると確信しています)。
してみましょうinitReducer
に設定する準備ができて、フラグのために成功するために持っている各要求のフラグ持っ-Statetrue
の両方の* _DATA_SUCCESSアクションを減らすことをinitReducer
:
init.reducer.ts
export interface InitState = {
characterSuccess: boolean,
vehicleSuccess: boolean,
ready: boolean
}
const initialState = {
characterSuccess = false,
vehicleSuccess = false,
ready = false
};
export const initReducer (state: InitState = initialState, action: Action): InitState {
switch (action.type) {
/* ...
* other cases, like INITIALIZING or INITIALIZING_ERROR...
*/
case CharacterActions.CHARACTER_DATA_SUCCESS: {
/* set characterSuccess to true.
*
* if vehicleSuccess is already true
* this means that both requests completed successfully
* otherwise ready will stay false until the second request completes
*/
return Object.assign({}, state, {
characterSuccess: true
ready: state.vehicleSuccess
});
}
case VehicleActions.VEHICLE_DATA_SUCCESS: {
/* set vehicleSuccess to true.
*
* if characterSuccess is already true
* this means that both requests completed successfully
* otherwise ready will stay false until the second request completes
*/
return Object.assign({}, state, {
vehicleSuccess: true,
ready: state.characterSuccess
});
}
default:
return state;
}
}
initReducer
現在初期化しているかどうかを追跡するためだけに作成した場合は、レデューサー全体を省略して、代わりに派生状態を計算するセレクターを使用できます。再選択ライブラリ
を使用するのが好きです。変更が発生したときにのみ再計算する効率的なセレクター(=メモ化されたセレクター)を作成できるからです。
まず、Vehicles-reducerとCharacters-reducerの両方の状態形状にloading
-ready
フラグと-フラグを追加します。
次に、レデューサーレベルでセレクター関数を追加します。
VehiclesReducerの例:
Vehicle.reducer.ts (Characters-reducerについても同じことを繰り返します)
export interface VehicleState {
// vehicle ids and entities etc...
loading: boolean;
ready: boolean;
}
const initialState: VehicleState = {
// other init values
loading: false,
ready: false
}
export function reducer(state = initialState, action: Action): VehicleState {
switch (action.type) {
// other cases...
case VehicleActions.INIT_VEHICLES: {
return Object.assign({}, state, {
loading: true,
ready: false
});
}
case VehicleActions.VEHICLE_DATA_SUCCESS: {
return Object.assign({}, state, {
/* other reducer logic like
* entities: action.payload
*/
loading: false,
ready: true
});
}
default:
return state;
}
}
// Selector functions
export const getLoading = (state: VehicleState) => state.loading;
export const getReady = (state: VehicleState) => state.ready;
次に、ルートリデューサーまたはセレクターを配置する追加ファイルで、目的の派生状態を提供するセレクターを作成します。
セレクター.ts
import { MyGlobalAppState } from './root.reducer';
import * as fromVehicle from './vehicle.reducer';
import * as fromCharacter from './character.reducer';
import { createSelector } from 'reselect';
// selector for vehicle-state
export const getVehicleState = (state: MyGlobalAppState) => state.vehicle;
// selector for character-state
export const getCharacterState = (state: MyGlobalAppState) => state.character;
// selectors from vehicle
export const getVehicleLoading = createSelector(getVehicleState, fromVehicle.getLoading);
export const getVehicleReady = createSelector(getVehicleState, fromVehicle.getReady);
// selectors from character
export const getCharacterLoading = createSelector(getCharacterState, fromCharacter.getLoading);
export const getCharacterReady = createSelector(getCharacterState, fromCharacter.getReady);
// combined selectors that will calculate a derived state from both vehicle-state and character-state
export const getLoading = createSelector(getVehicleLoading, getCharacterLoading, (vehicle, character) => {
return (vehicle || character);
});
export const getReady = createSelector(getVehicleReady, getCharacterReady, (vehicle, character) => {
return (vehicle && character);
});
これで、コンポーネントで次のセレクターを使用できます。
import * as selectors from './selectors';
let loading$ = this.store.select(selectors.getLoading);
let ready$ = this.store.select(selectors.getReady);
loading$.subscribe(loading => console.log(loading)); // will emit true when requests are still running
ready$.subscribe(ready => console.log(ready)); // will emit true when both requests where successful
このアプローチはより冗長かもしれませんが、よりクリーンで、確立されたreduxのプラクティスに従います。そして、全体を省略できるかもしれませんinitReducer
。
これまでセレクターを使用したことがない場合は、ngrx-example-appに表示されます。
アップデートについて:
ルーターを使用しているため、たとえば、ルーターガードを使用して、初期化が完了するまでルートのアクティブ化を保留できます。CanActivateインターフェースを実装します。
@Injectable()
export class InitializedGuard implements CanActivate {
constructor(private store: Store<MyGlobalAppState>) { }
canActivate(): Observable<boolean> {
return this.store.select(fromRoot.getInitState) // select initialized from store
.filter(initialized => initialized === true)
.take(1)
}
}
次に、ガードをルートに追加します。
{
path: 'vehicle/:id',
component: VehicleComponent,
canActivate: [ InitializedGuard ]
}
ルートアクティベーションガードもngrx-example-appに表示されます。こちらをご覧ください
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加