为什么我的@Effect用Angular 6中的ngrx覆盖现有状态?

时间:2018-08-03 15:15:55

标签: javascript angular ngrx ngrx-effects

我正在Angular 6应用程序中使用ngrx,我可以成功地从数据库中加载数据并将其显示在屏幕上。但是,当我导航至应用程序中的新页面然后返回时,状态不会保留,并且似乎再次调用@Effect并再次从数据库加载数据。这是我的代码:

效果

export class ProductEffects {
    constructor(private productService: ProductService, private actions$: Actions) { }

    @Effect()
    loadProducts$: Observable<Action> = this.actions$.pipe(
        ofType(productActions.LOAD_ACTION),
        switchMap(action =>
            this.productsService.getProductDetails().pipe(
                map(product => new productActions.LoadSuccess(product)),
                catchError(err => of(new productActions.LoadError(err)))
            )
        )
    );

减速器

export interface ProductState {
    product: Product;
}

const initialState: ProductState = {
    product: {}
};

export function reducer(state = initialState, action: Action) {
    switch (action.type) {
        case SET_PRODUCT:
            return { ...state, product: (action as SetProductAction).payload };

        case LOAD_SUCCESS:
            return { ...state, product: (action as LoadSuccess).payload, error: '' };

        default: return state;
    }
}

操作

export const SET_PRODUCT = '[Product] Set Product';
export const LOAD = '[Product] Load';
export const LOAD_SUCCESS = '[Product] Load Success';
export const LOAD_ERROR = '[Product] Load Error';

export class SetProductAction implements Action {
    readonly type = SET_PRODUCT;
    constructor(public payload: Product) { }
}

export class Load implements Action {
    readonly type = LOAD;
}

export class LoadSuccess implements Action {
    readonly type = LOAD_SUCCESS;
    constructor(public payload: Product) { }
}

export type ProductActions = SetProduct | Load | LoadSuccess;

商店

export interface State extends fromRoot.AppState {
    product: fromProduct.ProductState;
}

// selectors
const getProductState = createFeatureSelector<fromProduct.ProductState>('product');

export const getProduct = createSelector(
    getProductState,
    state => state.product
}

组件

products$: Observable<Product>;

constructor(private store: Store<fromProduct.State>) { }

ngOnInit() {
    this.store.dispatch(new Load());
    this.products$ = this.store.pipe(select(fromProduct.getProduct));
}

1 个答案:

答案 0 :(得分:1)

您的ngrx实施对我来说似乎还可以。您描述的是绝对正常的行为。一旦您离开某个页面,就会破坏该组件并创建一个新组件,即调用ngOnInit。如果将“加载”逻辑放在ngOnInit中,则每次导航到此页面时都会加载状态。