如何才能捕获两个(或更多)@ngrx / store操作并在组件中保留订阅直到发生这种情况?

时间:2017-06-06 16:04:23

标签: angular ngrx ngrx-effects ngrx-store

在我的主要组件中,我开始初始化我的数据:

_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 ,我跟随你的第一个和更快的adwise。

索里提出了额外的问题,但我真的很难找到好的做法 下一步。如何保存此订阅(内部组件)直到我的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;
  });  
}  

要重现我的问题,只需按下列表中的其中一辆车即可。订阅回调没有解雇。然后按F5 - &gt;现在车辆装载,beacouse回调按设计被解雇。

完整的源代码在这里:GitHub, 最后一个版本正在运行on GitHub Pages

1 个答案:

答案 0 :(得分:4)

我可以想到两种方法(我确定还有其他方法):

1。在减速机

initReducer - 状态为每个请求都有标记,通过减少true中的* _DATA_SUCCESS操作,必须成功将ready-flag设置为initReducer / p>

<强> 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;
    }
}

2。使用选择器

如果您创建initReducer只是为了跟踪您当前是否正在初始化,则可以省略整个减速器并使用选择器来计算派生状态。
我喜欢使用reselect库,因为它允许您创建有效的选择器,只在发生更改时重新计算(= memoized selectors)。

首先,在车辆和字符减速器的状态形状中添加loading - 和ready - 标志。
然后,在减速器级别添加选择器功能 VehiclesReducer的示例:

<强> vehicle.reducer.ts (对字符缩减器重复相同)

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;

接下来,在root-reducer或放置选择器的附加文件中,组合选择器,为您提供所需的派生状态:

<强> selectors.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中展示,看看here