Supporting the effect in our component

We don't need to do much in our component. Of course, we need to add some things in the template to support adding a product. In terms of NgRx, we just need to dispatch the ADD_PRODUCT action. Let's have a look at the code:

import { Component, OnInit } from "@angular/core";
import { AppState } from "../app-state";
import { Store } from "@ngrx/store";
import { fetchProducts, addProduct } from "./product.actions";
import { getList, isLoading, getError } from "./products.selectors";

@Component({
selector: "products",
template: `
<div>
<input [(ngModel)]="newProduct" placeholder="new product..." />
<button (click)="addNewProduct()"></button>
</div
>
<div *ngFor="let product of products$ | async">
Product: {{ product.name }}
</div>
<div *ngIf="loading$ | async; let loading">
<div *ngIf="loading">
loading...
</div>
</div>
<div *ngIf="error$ | async; let error">
{{ error }}
</div>
`
})
export class ProductsComponent implements OnInit {
products$;
loading$;
error$;
newProduct: string;

constructor(private store: Store<AppState>) {
this.products$ = this.store.select(getList);
this.loading$ = store.select(isLoading);
this.error$ = store.select(getError);
}

ngOnInit() {
this.store.dispatch(fetchProducts());
}

addNewProduct() {
this.store.dispatch(addProduct(this.newProduct));
this.newProduct = "";
}

}

Ok, from this code we set up an input control and a button to be able to handle the user inputting a new product. For the class, we added the newProduct field and we also added the addNewProduct() method that, in its body, invokes the addProduct(), method and thereby passes an ADD_PRODUCT action. We really don't need to do more. Our product addition sets the loading state before carrying out the HTTP call, so we can show a spinner if we want, and our error state picks up on any errors that might occur and presents them in the UI. Lastly, don't forget to add the FormsModule to the import property in the product.module.ts.

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

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