Navigating through dispatch

Now that we have our router store properly set up, we can actually start thinking in terms of dispatching actions, even for routes. OK, what does that mean? Well, imagine we are thinking more and more in dispatching actions; it makes our world simpler. When you dispatch an action, an HTTP call happens, and, in dispatching an action, the application routes you where you want to go.

This isn't really a feature of the router store, but a way you can look at it. A way to implement this is by writing your own effect that responds to a route action, and, as a result, you call the router service and perform the navigation. Let's summarize what we just said in a bullet list and carry out the resulting steps:

  1. Set up some routing constants.
  2. Set up some routing actions.
  3. Write an effect that listens to routing actions and performs routing inside of the effect.

Here is Step 1:

// routing-constants.ts
export const PRODUCTS = 'Navigation products';
export const TODOS = 'Navigation todos';

export interface RoutingAction implements Action {
type: string;
payload: { url: string, query: { page: number } ;}
}

OK, our next step is to define a set of action creators so we can set off a certain behavior when a specific action occurs:

// router-actions.ts
import { PRODUCTS, TODOS } from './routing-constants';

export const gotoProducts = (pageNo) => ({
type: PRODUCTS,
payload: { url: '/products', query: { page: pageNo } }
});

export const gotoTodo = (pageNo) => ({
type: TODOS,
payload: { url: '/todos', query: { page: pageNo } }
})

Our next step is our effect, which would now be able to respond to the preceding actions:

// routing-effects.ts
import { PRODUCTS, TODOS } from './routing-constants';
import { gotoProducts, gotoTodo }

export class RoutingEffects {
@Effect({ dispatch: false }) routingProducts$ = this.actions$
.ofType(PRODUCTS)
.tap(action => {
this.router.navigate('/products')
})

@Effect({ dispatch: false }) routingTodos$ = this.actions$
.ofType(TODOS)
.tap(action => {
this.router.navigate('/todos');
})


constructor(
private router: Router,
private actions$: Actions) {

}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.62.34