天天看點

@ngrx/router-store 在 SAP 電商雲 Spartacus UI 開發中的作用

标題:@ngrx/router-store 的作用

官網

用于将 Angular Router 與 Store 連接配接的綁定。 在每個路由器導航周期中,會分派多個動作,讓您可以監聽路由器狀态的變化。 然後,您可以從路由器的狀态中選擇資料,為您的應用程式提供附加資訊。

安裝:

npm install @ngrx/router-store --save

之後,在 package.json 會出現一個依賴:

@ngrx/router-store 在 SAP 電商雲 Spartacus UI 開發中的作用

action

Router Store 提供了五個按特定順序排程的導航操作。 Router Store 提供的 routerReducer 使用 actions 給出的最新路由器狀态更新其狀态。 預設情況下,我們建議使用我們提供的 creator function.

routerRequestAction

在每次導航開始時,路由器将排程 ROUTER_REQUEST action.Spartacus 沒有用到這個 action.

routerNavigationAction

在導航期間,在任何 guard 或 resolvers 運作之前,路由器将排程 ROUTER_NAVIGATION 操作。

Spartacus 裡使用到了這個 action:

@ngrx/router-store 在 SAP 電商雲 Spartacus UI 開發中的作用
@ngrx/router-store 在 SAP 電商雲 Spartacus UI 開發中的作用

navigation target:

@ngrx/router-store 在 SAP 電商雲 Spartacus UI 開發中的作用

routerNavigatedAction

成功導航後,路由器将排程 ROUTER_NAVIGATED action.

事件 ROUTER_NAVIGATION 觸發時,home page 的 page guard 和 resolver 還沒有執行:

@ngrx/router-store 在 SAP 電商雲 Spartacus UI 開發中的作用

事件 ROUTER_NAVIGATED 發生時,跳轉已經成功完成了。是以 nextState 為 undefined.

@ngrx/router-store 在 SAP 電商雲 Spartacus UI 開發中的作用

是以,判斷目前是否處于 navigating 即正在導航,隻需要從 store 裡,檢查 nextState 是否為空就行了。

發生的時序如下:

Success case

ROUTER_REQUEST

ROUTER_NAVIGATION

ROUTER_NAVIGATED

Error / Cancel case (with early Navigation Action Timing):

ROUTER_CANCEL / ROUTER_ERROR

Error / Cancel case (with late Navigation Action Timing):

繼續閱讀