2017-05-30 60 views
3

我正在學習Angular 2,我正在嘗試用戶ngrx/store,但我在某些特殊情況下遇到了一些困難。ngrx /存儲效果嵌套對象

示例我試圖刪除父對象。我想要做的是去除子對象。

這裏是我的實體:

export class Discussion { 
    id: string; 
    name: string; 
    createdAt: Date; 
    posts: Post[]; 
} 

export class Post { 
    id: string; 
    title: string; 
    data: string; 
    createdAt: Date; 
    comments: Comment[]; 
} 

export class Comment { 
    id: string; 
    data: string; 
    createdAt: Date; 
} 

我使用normalizr打平我的狀態,所以我存儲的討論將是這樣的:

{ 
    id: "1", 
    name: "First dicussion", 
    createdAt: "...", 
    posts: ["1", "2", "3", "5"] 
} 

我有3個減速,爲討論一個減速機,另一個是郵件,最後是評論。所有reducer都處理它自己類型的delete操作。這裏是討論減速的一個例子:

export function reducer(state = initialState, action: discussion.Actions): State { 
switch (action.type) { 
    case discussion.REMOVE: { 
     const idToRemove = action.payload; 
     const newEntities = state.entities; 
     delete newEntities[idToRemove]; 
     return Object.assign({}, state, { 
      entities: newEntities 
     }); 
    } 
}} 

我的動作是這樣的:

export class RemoveAction implements Action { 
readonly type = REMOVE; 

/** 
* Constructor 
* @param payload The id of the discussion to remove 
*/ 
constructor(public payload: string) { } 
} 

當我刪除的討論,我想刪除相關的討論和帖子的效果將刪除 評論帖與已刪除的帖子有關。 我用NGRX的效果要這麼做,所以我用這個效果:

@Effect() 
removeDiscussion: Observable<Action> = this._actions 
.ofType(dicussion.REMOVE) 
.map((action: discussion.RemoveAction) => action.payload) 
.mergeMap(discId => { 

    // How to get posts from discussion id ??? 

    // Fire related Actions 
    return [ 
     new posts.RemoveAction(postsToRemove) 
    ]; 
}); 

我的問題是如何獲得的職位,從討論的標識去掉?

感謝您的閱讀。

回答

2

您可以使用withLatestFrom訪問商店。
import 'rxjs/add/operator/withLatestFrom';

注入店的影響類:

constructor(private _actions: Actions, private store: Store<fromRoot.State>) 

使用它的效果:

@Effect() 
removeDiscussion: Observable<Action> = this._actions 
    .ofType(dicussion.REMOVE) 
    .map((action: discussion.RemoveAction) => action.payload) 
    .withLatestFrom(this.store, (payload, state) => ({ discId: payload, state })) 
    .mergeMap(({ discId, state }) => { 
     // access the posts array of the discussion 
     const postsToRemove = state.discussions[discId].posts; 

     // Fire related Actions 
     return [ 
      new posts.RemoveAction(postsToRemove) 
     ]; 
    }); 

語法.mergeMap(({ discId, state }) => ...destructuring
如果你不喜歡這種語法,它可以用.mergeMap((payloadAndState) => ...替代。然後你會通過做discIdpayloadAndState.discId

+0

你好mtx, 感謝您的回答。這是我正在尋找的。 我不知道withLatestFrom,所以我想知道如何訪問狀態對象。 此外,解構語法非常酷,也爲此感謝。 對於使用withLatestFrom時出錯的人,請勿僞造添加'import'rxjs/add/operator/withLatestFrom';'。由於我是初學者,所以忘了添加它。 – Lopeur

+0

很高興我能幫到你。如果有人遇到這個問題,我會在答案中加入進口聲明。感謝提示! – mtx