代码之家  ›  专栏  ›  技术社区  ›  J-man

为什么我的@效果在角6中覆盖了现有状态?

  •  0
  • J-man  · 技术社区  · 6 年前

    我在Angular6应用程序中使用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 回复  |  直到 6 年前
        1
  •  1
  •   René Winkler    6 年前

    你的ngrx实现在我看来一切正常。你所描述的是一种绝对正常的行为。一旦你离开一个页面,组件就会被破坏,新的组件就会被创建,即ngOnInit被调用。如果将加载逻辑放在ngOnInit中,则每次导航到此页时都会加载状态。