Adding another effect

Now we are finally ready to construct our effect. It's going to look very similar to the existing one:

import { Injectable } from "@angular/core";
import { HttpClient } from "@angular/common/http";
import { Action } from "@ngrx/store";
import { Actions, Effect, ofType } from "@ngrx/effects";
import { Observable } from "rxjs/Observable";
import { of } from "rxjs/observable/of";
import "rxjs/add/observable/of";
import {
catchError,
map,
mergeMap,
delay,
tap,
switchMap
}
from "rxjs/operators";
import { FETCHING_PRODUCTS, ADD_PRODUCT } from "./product.constants";
import {
fetchProductsSuccessfully,
fetchError,
addProductSuccessfully,
addProductError
}
from "./product.actions";
import { Product } from "./product.model";
import { ActionPayload } from "../interfaces";

@Injectable()
export class ProductEffects {
@Effect() productsAdd$: Observable<Action> = this.actions$.pipe(
ofType(ADD_PRODUCT),
switchMap(action =>
this.http.post("products/", action.payload).pipe(
map(addProductSuccessfully),
catchError((err) => of(addProductError(err)))</strong>
)
)
);

@Effect() productsGet$: Observable<Action> = this.actions$.pipe(
ofType(FETCHING_PRODUCTS),
switchMap(action =>
this.http.get("data/products.json").pipe(
delay(3000),
map(fetchProductsSuccessfully),
catchError((err) => of(fetchError(err)))
)
)
);

constructor(
private http: HttpClient,
private actions$: Actions<ActionPayload<Product>>
) {}
}

The first thing we do here is to reuse our ProductEffects class and add a new member productsAdd$ to it. While at it, we rename products$ to productsGet$. As long as we are dealing with products we can keep on adding to this class.

The similarities we see with the existing effect is that we set up our ofType() operator to listen for a dispatched action of our choice. Thereafter, we continue with our side effect, that is the call to the HttpClient service that ends up being an HTTP POST call. 

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

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