Skip to main content

NgRx(Version 12) | An Angular State Management Using @ngrx/data

In this article, we are going to implement an Angular application state management using @ngrx/data.

@ngrx/data:

In a general angular application using NgRx Store, Effects, and Entity libraries made us to write a huge number of actions, reducers, effects, selectors, HTTP API calls per entity model. It leads to a lot of repetitive code to create, maintain and test.

Using NgRx Data we can reduce our code to very little despite having a large number of entity models in our application. The NgRx Data is an abstraction over the Store, Effects, and Entity that radically reduces the amount of code we have to write. By gaining the abstraction benefit, we are going to lose our direct interaction with NgRx libraries.

Ngrx Store Flow:
  • Using Ngrx we never contact the store directly, every store operation is carried out by the NgRx store implicitly.
  • Our main point of contact is EntityCollectionService.
  • Using EntityCollectionService for each entity can invoke API calls with default method like 'getAll()', 'add()', 'delete()', 'update()'.
  • So from our angular component, we need to invoke any one method from the 'EntityCollectionService'. Then internally EntityAction gets triggered and raises an action method to invoke the API call based on our entity model.
  • On API success EntityAction raises a new action method to invoke 'EntityCollectionReducers'.
  • So from the 'EntityCollectionReducer' appropriate reducer gets invoked and updates the data to store.
  • On state change, selectors will fetch the data into the angular component from the store.

Create An Angular Application:

To start our demo let's create an angular sample application. While creating a sample make sure to enable routing because in this demo we are going to implement lazy loading as well.
Install Angular CLI:
npm install -g @angular/cli

Command To Create Angular Application:
ng new your-project-name

Let's create a new module like 'shop' for our demo. Run the below command to create module and route files.
ng g module shop --routing


Let's add components like 'products'. Run the below command to generated component files.
ng g component shop/products


Now let's define the route.
app/shop/shop-routing.module.ts:
import { ProductsComponent } from './products/products.component';

const routes: Routes = [
  {
    path:'',
    component: ProductsComponent
  },
];
app/app-routing.module.ts:
const routes: Routes = [{
  path:'',
  loadChildren:() => import('./shop/shop.module').then(_ => _.ShopModule)
}];

Install Bootstrap And Configure Menu:

npm install bootstrap

Include the Bootstrap CSS and js files into the 'angular.json' file 

Now add the Bootstrap menu in the 'app.component.html'
app/app.component.html:
<nav class="navbar navbar-expand-lg bg-dark">
  <div class="container-fluid">
    <a href="#" class="navbar-brand text-white"> Shopping </a>
  </div>
</nav>

Install And Configure @ngrx/data:

Now let's install '@ngrx/data' and its dependent libraries.
Command To Install Store:
npm install @ngrx/store --save

Command To Install Effects:
npm install @ngrx/effects --save

Command To Install NgRx Entity:
npm install @ngrx/entity --save

Command To Install NgRx Data:
npm install @ngrx/data --save

Command To Install Dev Tool(Optional):
npm install @ngrx/store-devtools --save

Now let's import the required modules into the 'AppModule'.
app/app.module.ts:
import { HttpClientModule } from '@angular/common/http';
import { EntityDataModule } from '@ngrx/data';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { environment } from 'src/environments/environment';

// existing code hidden for display purpose

@NgModule({
  imports: [
    AppRoutingModule,
    HttpClientModule,
    StoreModule.forRoot({}),
    EffectsModule.forRoot([]),
    EntityDataModule.forRoot({}),
    StoreDevtoolsModule.instrument({
      maxAge: 25, // Retains last 25 states
      logOnly: environment.production, // Restrict extension to log-only mode
      autoPause: true, // Pauses recording actions and state changes when the extension window is not open
    })
  ]
})
export class AppModule { }
  • Important note the 'EntityDataModule' must register after 'StoreModule' and 'EffectsModule'.
  • Also notice HttpClientModule also imported
  • The 'StoreDevToolsModule' for enabling the chrome extension debugger for our store.

Register Entity Models Into Entity MetaData:

Let's first create the response model from my API endpoint. Create a 'product.model.ts' in the 'shop/products' folder.
app/shop/products/product.model.ts:
export interface ProductModel {
  productId: number;
  name: string;
  manufacturer: string;
  description: string;
  price: number;
}
To use NgRx Data all our application models should be registered within Entity MetaData. Since I'm using a module-based application let's create a new file in 'shop' folder like 'shop-entity-metadata.ts'.
app/shop/shop-entity-metadata.ts:
import { EntityMetadataMap } from "@ngrx/data";
import { ProductModel } from "./products/product.model";

export const shopEntityMetaData:EntityMetadataMap ={
    Product:{
        selectId: (prodcut:ProductModel) => prodcut.productId,
        /*
          Options props
          ==================
          filterFn,
          sortComparer,
          etc
         */
    }
}
  • Here 'EtntiyMetadataMap' loads from the '@ngrx/data'. Here we have to register all the entity models here.
  • (Line: 5) Here defined the entity name like 'Product'. This name plays a very crucial role in our NgRx data. By pluralizing the entity name like 'Products' NgRx Data will generate the URLs of our API.
  • In general, our entity model should contain the primary key property mostly 'Id' to work with NgRx Data. By default 'Id' property will be recognized by the Ngrx Data, but if we want to specify our custom property as the primary key then we have to use the 'selectId' property like above.
  • Along with 'selectId' property, EntityMetadataMap provides so many different props, so explore them if needed.
Now register our Entity Metadata into the 'ShopModule'.
app/shop/shop.modulet.ts:
import { EntityDefinitionService } from '@ngrx/data';
import { shopEntityMetaData } from './shop-entity-metadata';

/* code hidden for disply purpose */

@NgModule({
})
export class ShopModule {
  constructor(entityDefinitionService: EntityDefinitionService) {
    entityDefinitionService.registerMetadataMap(shopEntityMetaData);
  }
}
  • Here registering our Entity MetaData with the help of 'EntityDefinitionService' injecting into the module constructor.

Use EntityCollectionService:

An EntityCollectionService is a main tool for the NgRx data to handle the 'distpacher' and 'selectors$' that manages an entity collection cached in the NgRx store.

The 'Dispatcher' features a command method that dispatches entity actions to the Ngrx store. So these dispatcher commands can update the store directly or invoke the HTTP request. In case of invoking HTTP requests, on successful response again new action will be invoked to updates the entity collection in the store.

The 'selectors$' are properties returning selector observables. Each observable watches for a specific change in the cached entity collection and emits the changed value.

Now in our component let's use EntityCollectionService to use all NgRx Data features.
app/shop/products/products.component.ts:
import { Component, OnInit } from '@angular/core';
import {
  EntityCollectionService,
  EntityCollectionServiceFactory,
} from '@ngrx/data';
import { Observable } from 'rxjs';
import { ProductModel } from './product.model';

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
})
export class ProductsComponent implements OnInit {
  allProducts$: Observable<ProductModel[]>;
  productService: EntityCollectionService<ProductModel>;
  constructor(entityCollectionServiceFactory: EntityCollectionServiceFactory) {
    this.productService =
      entityCollectionServiceFactory.create<ProductModel>("Product");
    this.allProducts$ = this.productService.entities$;
  }

  ngOnInit(): void {
    this.productService.getAll();
  }
}
  • (Line: 15) The 'allProducts$' variable of type 'Observable<ProductModel[]>'. This variable holds data that need to be bind to the UI.
  • (Line: 16) The 'productService' variable of type 'EntityCollectionService<ProductModel>'. This variable represents our 'Product' entity collection. This variable will be our key to interact with the EntityCollection of our store. Using the 'EntityCollectionService' we can use predefined 'dispatchers' and 'selectors$' to communicate with the store.
  • (Line: 17) Injecting the 'EntityCollectionServiceFactory' that loads from the '@ngrx/data'.
  • (Line: 18&19) Using 'EntityCollectionServiceFactory', we will create instance of 'EntityCollectionService' of type 'Products. To do that we have to use a name like 'Product'(This name must match with one of the property names of the 'EntityMetadataMap')
  • (Line: 20) The 'entities$' is one of the EntityCollectionService 'selectors$'.
  • (Line: 24) The 'getAll()' is one of the EntityCollectionService 'dispatcher'.
app/shop/products/products.component.html:
<div class="container">
  <div class="row">
    <table class="table table-dark table-striped m-3">
      <thead>
        <tr>
          <th scope="col">Product Id</th>
          <th scope="col">Name</th>
          <th scope="col">Manufacturer</th>
          <th scope="col">Description</th>
          <th scope="col">Price</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let item of allProducts$ | async">
          <th scope="row">{{item.productId}}</th>
          <td>{{item.name}}}</td>
          <td>{{item.manufacturer}}</td>
          <td>{{item.description}}</td>
          <td>{{item.price}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
  • Binding the data from the variable 'allProducts$'.
Now if you run our application we can see an API call gets invoked that due to calling 'getAll()' method in the ngOnInit() method. But the API gets failed because it's auto framed URL.

Implement DefaultHttpUrlGenerator:

Now to configure my API domain we are going to implement DefaultHttpUrlGenerator. But one disadvantage in this approach, if our API is like 'http://localhost:5000/api/products' then the same URL will be used for all HTTP requests like GET, POST, PUT, DELETE(How to overcome this disadvantage can be explored in upcoming steps).

So now in the 'app' folder let's create a new file like 'custom-url-http-general-generator.service.ts'.
app/custom-url-http-general-generator.service.ts:
import { Injectable } from '@angular/core';
import {
  DefaultHttpUrlGenerator,
  HttpResourceUrls,
  Pluralizer,
} from '@ngrx/data';

@Injectable({
  providedIn: 'root',
})
export class CustomUrlHttpGeneralGeneratorService extends DefaultHttpUrlGenerator {
  constructor(private myPluralizer: Pluralizer) {
    super(myPluralizer);
  }

  protected getResourceUrls(
    entityName: string,
    root: string
  ): HttpResourceUrls {
    let resourceUrls = this.knownHttpResourceUrls[entityName];
    if (entityName == 'Product') {
      const url = 'https://localhost:44324/api/Products/';
      resourceUrls = {
        entityResourceUrl: url,
        collectionResourceUrl: url,
      };
      this.registerHttpResourceUrls({ [entityName]: resourceUrls });
    }

    return resourceUrls;
  }
}
  • Here service gets executed for every 'dispatcher' method of 'EntityCollectionService'. So here based on the entity name we are overriding the URL.
Now register our new service into the 'AppModule'.
app/app.module.ts:
import { EntityDataModule, HttpUrlGenerator } from '@ngrx/data';
import { CustomUrlHttpGeneralGeneratorService } from './custom-url-http-general-generator.service';

// code hidden for display purpose

@NgModule({
  
  providers: [
    { provide: HttpUrlGenerator, useClass: CustomUrlHttpGeneralGeneratorService }
  ]
})
export class AppModule { }
Now run the application again and can see the output like below.

Add Operation:

Now we are going to explore the 'Add Operation' behavior with NgRx Data.
app/shop/products/products.component.ts:
import { Component, OnInit } from '@angular/core';
import {
  EntityCollectionService,
  EntityCollectionServiceFactory,
} from '@ngrx/data';
import { Observable } from 'rxjs';
import { ProductModel } from './product.model';
declare var window: any;

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
})
export class ProductsComponent implements OnInit {
  allProducts$: Observable<ProductModel[]>;
  productService: EntityCollectionService<ProductModel>;
  myModal: any;
  productForm: ProductModel = {
    description: '',
    manufacturer: '',
    name: '',
    price: 0,
    productId: 0,
  };
  modalTitle:string = ''
  constructor(entityCollectionServiceFactory: EntityCollectionServiceFactory) {
    this.productService =
      entityCollectionServiceFactory.create<ProductModel>('Product');
    this.allProducts$ = this.productService.entities$;
  }

  ngOnInit(): void {
    this.productService.getAll();
    this.myModal = new window.bootstrap.Modal(
      document.getElementById('productsModal'),
      {
        keyboard: false,
      }
    );
  }

  openModal(productId: number) {
    if (productId == 0) {
      this.modalTitle = "Add Product";
      this.productForm = {
        description: '',
        manufacturer: '',
        name: '',
        price: 0,
        productId: 0,
      };
    }
    this.myModal.show();
  }

  saveorupdate() {
    if (this.productForm.productId == 0) {
      this.productService.add(this.productForm).subscribe(_ => this.myModal.hide());
    }
  }
}
  • (Line: 8) The 'window' instance is declared.
  • (Line: 18) The 'myModal' variable to store the instance of the Bootstrap Modal.
  • (Line: 19-25) The 'productForm' variable to maintain the form data for to add or update.
  • (Line: 26) The 'modalTitle' variable for Bootstrap Modal title.
  • (Line: 35-40) Assigning the instance of the Bootstrap Modal popup to 'myModal' variable.
  • (Line: 43-53) The 'OpenModal()' method going to be used for opening the Modal popup form. This method will be commonly used for both 'Add' and 'Update' operations.
  • (Line: 59) Invoking 'add()' method from 'EntityCollectionService'. So 'add()' method invokes the API call and on success, API call the new record will be added to EntityCollection of the store.
app/shop/products/products.component.html:
<div class="container">
  <div class="row m-1">
    <div class="col text-center">
      <button type="button" class="btn btn-primary" (click)="openModal(0)">
        Add Product
      </button>
    </div>
  </div>
  <div class="row">
    <table class="table table-dark table-striped m-2">
      <!-- code hidden for display purspose -->
    </table>
  </div>
</div>

<!-- Modal -->
<div
  class="modal fade"
  id="productsModal"
  tabindex="-1"
  aria-labelledby="exampleModalLabel"
  aria-hidden="true"
>
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
        <button
          type="button"
          class="btn-close"
          data-bs-dismiss="modal"
          aria-label="Close"
        ></button>
      </div>
      <div class="modal-body">
        <div class="container">
          <input type="hidden" id="productId" [(ngModel)]="productForm.productId">
          <div class="row">
            <div class="mb-3">
              <label for="name" class="form-label">Product Name</label>
              <input type="text" class="form-control" id="name" [(ngModel)]="productForm.name"/>
            </div>
          </div>
          <div class="row">
            <div class="mb-3">
              <label for="manufacturer" class="form-label">Manufacturer</label>
              <input type="text" class="form-control" id="manufacturer"[(ngModel)]="productForm.manufacturer" />
            </div>
          </div>
          <div class="row">
            <div class="mb-3">
              <label for="exampleFormControlInput1" class="form-label"
                >Description</label
              >
              <input type="text" class="form-control" id="description" [(ngModel)]="productForm.description" />
            </div>
          </div>
          <div class="row">
            <div class="mb-3">
              <label for="exampleFormControlInput1" class="form-label"
                >Price</label
              >
              <input type="text" class="form-control" id="price" [(ngModel)]="productForm.price" />
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button
            type="button"
            class="btn btn-secondary"
            data-bs-dismiss="modal"
          >
            Close
          </button>
          <button type="button" class="btn btn-primary" (click)="saveorupdate()">Save changes</button>
        </div>
      </div>
    </div>
  </div>
</div>
  • (Line: 4-6) The 'Add' button, its click event registered with 'openModal()' method.
  • Rendered Bootstrap Modal that contains form fields enabled angular 2-way binding.
  • (Line: 75) The 'Save Changes' button, its click event registered with 'saveorupdate()' method.
Since enabled 2-way binding for the above Bootstrap Modal, we have to import the 'FormModule' into our 'ShopModule'.


Update Operation:

Now let's try to explore update operation.
app/shop/products/products.component.ts:
import { Component, OnInit } from '@angular/core';
import {
  EntityCollectionService,
  EntityCollectionServiceFactory,
} from '@ngrx/data';
import { Observable } from 'rxjs';
import { ProductModel } from './product.model';
declare var window: any;

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
})
export class ProductsComponent implements OnInit {
  allProducts$: Observable<ProductModel[]>;
  productService: EntityCollectionService<ProductModel>;
  myModal: any;
  productForm: ProductModel = {
    description: '',
    manufacturer: '',
    name: '',
    price: 0,
    productId: 0,
  };
  modalTitle: string = '';
  constructor(entityCollectionServiceFactory: EntityCollectionServiceFactory) {
    this.productService =
      entityCollectionServiceFactory.create<ProductModel>('Product');
    this.allProducts$ = this.productService.entities$;
  }

  ngOnInit(): void {
    this.productService.getAll();
    this.myModal = new window.bootstrap.Modal(
      document.getElementById('productsModal'),
      {
        keyboard: false,
      }
    );
  }

  openModal(productId: number) {
    if (productId == 0) {
      this.modalTitle = 'Add Product';
      this.productForm = {
        description: '',
        manufacturer: '',
        name: '',
        price: 0,
        productId: 0,
      };
    } else {
      this.modalTitle = 'Update Product';
      this.productService.entities$.subscribe((data) => {
        let filteredProduct = data.filter((_) => _.productId == productId)[0];
        this.productForm = {...filteredProduct};
      });
    }
    this.myModal.show();
  }

  saveorupdate() {
    if (this.productForm.productId == 0) {
      this.productService
        .add(this.productForm)
        .subscribe((_) => this.myModal.hide());
    } else {
      this.productService
        .update(this.productForm)
        .subscribe((_) => this.myModal.hide());
    }
  }
}
  • (Line: 54) Set the title for the modal popup.
  • (Line: 55-58) Filtering the product to be updated from 'entitis$' store selector. Result assigned to 'productForm' variable.
  • (Line: 69-71) Used 'update' dispatcher method of EntityServiceCollection.
app/shop/products/products.component.html:
<!-- code hidden for display purpose -->
<div class="container">
  <div class="row">
    <table class="table table-dark table-striped m-2">
      <thead>
        <tr>
          <th scope="col">Product Id</th>
          <th scope="col">Name</th>
          <th scope="col">Manufacturer</th>
          <th scope="col">Description</th>
          <th scope="col">Price</th>
          <th scope="col">Actions</th>
        </tr>
      </thead>
      <tbody>
        <tr *ngFor="let item of allProducts$ | async">
          <td>
            <button class="btn btn-primary" (click)="openModal(item.productId)">Edit</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>
  • (Line: 18) Enabled 'Edit' button for each record, this button register with a click event method like 'openModal()'
Now test the update operation, you can see the results of a successful update.

Delete Operation:

Let's explore the delete option here.
app/shop/products/products.component.ts:
import { Component, OnInit } from '@angular/core';
import {
  EntityCollectionService,
  EntityCollectionServiceFactory,
} from '@ngrx/data';
import { Observable } from 'rxjs';
import { ProductModel } from './product.model';
declare var window: any;

@Component({
  selector: 'app-products',
  templateUrl: './products.component.html',
  styleUrls: ['./products.component.css'],
})
export class ProductsComponent implements OnInit {
  allProducts$: Observable<ProductModel[]>;
  productService: EntityCollectionService<ProductModel>;
  myModal: any;
  productForm: ProductModel = {
    description: '',
    manufacturer: '',
    name: '',
    price: 0,
    productId: 0,
  };
  modalTitle: string = '';
  productIdToDelete :number = 0;
  deleteModal:any;
  constructor(entityCollectionServiceFactory: EntityCollectionServiceFactory) {
    this.productService =
      entityCollectionServiceFactory.create<ProductModel>('Product');
    this.allProducts$ = this.productService.entities$;
  }

  ngOnInit(): void {
    this.productService.getAll();
    this.myModal = new window.bootstrap.Modal(
      document.getElementById('productsModal'),
      {
        keyboard: false,
      }
    );
    this.deleteModal = new window.bootstrap.Modal(
      document.getElementById('deleteModal'),
      {
        keyboard: false,
      }
    )
  }

  openModal(productId: number) {
    if (productId == 0) {
      this.modalTitle = 'Add Product';
      this.productForm = {
        description: '',
        manufacturer: '',
        name: '',
        price: 0,
        productId: 0,
      };
    } else {
      this.modalTitle = 'Update Product';
      this.productService.entities$.subscribe((data) => {
        let filteredProduct = data.filter((_) => _.productId == productId)[0];
        this.productForm = {...filteredProduct};
      });
    }
    this.myModal.show();
  }

  saveorupdate() {
    if (this.productForm.productId == 0) {
      this.productService
        .add(this.productForm)
        .subscribe((_) => this.myModal.hide());
    } else {
      this.productService
        .update(this.productForm)
        .subscribe((_) => this.myModal.hide());
    }
  }

  openDeleteModal(productId: number){
    this.productIdToDelete = productId;
    this.deleteModal.show();
  }
  delete(){
    this.productService.delete(this.productIdToDelete)
    .subscribe(_ => this.deleteModal.hide());
  }
}
  • (Line: 27) The 'productIdToDelete' variable holds the record primary key that needs to be deleted.
  • (Line: 28) The 'deleteModal' variable is used to assign the Bootstrap Modal instance.
  • (Line: 43-48) Created the instance of the Bootstrap Modal and assigned it to the 'deleteModal' variable.
  • (Line: 83-86) The 'openDeleteModal' method to display the Bootstrap Modal for the delete confirmation.
  • (Line: 87-90) The 'delete()' dispatcher of EntityCollectionService used to delete the records.
app/shop/products/products.component.html:
<!-- Code Hidden For Display Purpose -->
<div class="container"> 
  <div class="row">
    <table class="table table-dark table-striped m-2">
      
      </thead>
      <tbody>
        <tr *ngFor="let item of allProducts$ | async">

            <button class="btn btn-primary" (click)="openModal(item.productId)">Edit</button>
            <button class="btn btn-danger" (click)="openDeleteModal(item.productId)">Delete</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

<!-- Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">Delete</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <h4>Confirm To Delete</h4>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="button" class="btn btn-danger" (click)="delete()">Delete</button>
      </div>
    </div>
  </div>
</div>
  • (Line: 11) The 'Delete' button registered with click event 'OpenDeleteModal'.
  • (Line: 20-36) Delete confirmation popup.
  • (Line: 32) The 'Delete' confirmation button registered with click event like 'delete()'.

Implement DefaultDataService<T>:

The '@ngrx/data' provides us a service like 'DefaultDataService<T>'. Using 'DefaultDataService<T>' we can override the default HTTP call methods like 'getAll()', 'add()', 'update()', 'delete()'. It helps to define our custom API URL and also allows us to modify the response data before saving into the EntityCollection of the store.

For our demo purpose, I will override the 'getAll()' method and also set the 'Price' value to '0' before saving it into the store. Let's create a service file like 'product.data.service.ts' in the 'products' folder.
app/shop/products/product.data.service.ts:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { DefaultDataService, HttpUrlGenerator } from '@ngrx/data';
import { Observable } from 'rxjs';
import { ProductModel } from './product.model';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root',
})
export class ProductDataService extends DefaultDataService<ProductModel> {
  constructor(http: HttpClient, httpUrlGenerator: HttpUrlGenerator) {
    super('Product', http, httpUrlGenerator);
  }

  getAll(): Observable<ProductModel[]> {
    return this.http.get('https://localhost:44324/api/Products/').pipe(
      map((data) => {
        if (!data) {
          return [];
        }
        return (data as ProductModel[]).map((d) => {
          return { ...d, price: 0 };
        });
      })
    );
  }
}
  • (Line: 11) Our service class 'ProductDataService' extends 'DefaultDataService<T>' that loads from '@ngrx/data'.
  • (Line: 13) To the base class passing 'Product'(name of the entity), 'http'(instance of the HTTPClient), 'httpUrlGenerator'(instance of the HttpUrlGenerator).
  • (Line: 16-27) Overriding the 'getAll()' method.
  • (Line: 17) Defined our full API URL.
  • (Line: 22-24) Modifying the API response data like 'Price' value set to '0'.
Now we need to inject our 'ProductDataService' into our lazy load module.
app/shop/shop.module.ts:
import { EntityDataService, EntityDefinitionService } from '@ngrx/data';
import { ProductDataService } from './products/product.data.service';
// code hidden for display purpose
@NgModule({
})
export class ShopModule {
  constructor(
    entityDefinitionService: EntityDefinitionService,
    entitydataService: EntityDataService,
    productDataService:ProductDataService
  ) {
    entityDefinitionService.registerMetadataMap(shopEntityMetadata);
    entitydataService.registerService('Product', productDataService);
  }
}
  • (Line: 13) Registered the 'ProductDataService' with the entity name 'Product'.

That's all about implementing '@ngrx/data' into the angular application.

Video Session:

Support Me!
Buy Me A Coffee PayPal Me

Wrapping Up:

Hopefully, I think this article delivered some useful information on Ngrx Data(Version 12). I love to have your feedback, suggestions, and better techniques in the comment section below.

Refer:

Follow Me:

Comments

Popular posts from this blog

Blazor WebAssembly Custom Authentication From Scratch

In this article, we are going to explore and implement custom authentication from the scratch. In this sample, we will use JWT authentication for user authentication. Main Building Blocks Of Blazor WebAssembly Authentication: The core concepts of blazor webassembly authentication are: AuthenticationStateProvider Service AuthorizeView Component Task<AuthenticationState> Cascading Property CascadingAuthenticationState Component AuthorizeRouteView Component AuthenticationStateProvider Service - this provider holds the authentication information about the login user. The 'GetAuthenticationStateAsync()' method in the Authentication state provider returns user AuthenticationState. The 'NotifyAuthenticationStateChaged()' to notify the latest user information within the components which using this AuthenticationStateProvider. AuthorizeView Component - displays different content depending on the user authorization state. This component uses the AuthenticationStateProvider

How Response Caching Works In Asp.Net Core

What Is Response Caching?: Response Caching means storing of response output and using stored response until it's under it's the expiration time. Response Caching approach cuts down some requests to the server and also reduces some workload on the server. Response Caching Headers: Response Caching carried out by the few Http based headers information between client and server. Main Response Caching Headers are like below Cache-Control Pragma Vary Cache-Control Header: Cache-Control header is the main header type for the response caching. Cache-Control will be decorated with the following directives. public - this directive indicates any cache may store the response. private - this directive allows to store response with respect to a single user and can't be stored with shared cache stores. max-age - this directive represents a time to hold a response in the cache. no-cache - this directive represents no storing of response and always fetch the fr

Endpoint Routing In Asp.Net Core

How Routing Works In  Core 2.1 And Below Versions?: In Asp.Net Core routing is configured using app.UseRouter() or app.UseMvc() middleware. app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); Here in Dotnet Core version 2.1 or below versions on the execution of route middleware request will be navigated appropriate controller matched to the route. An operation or functionality which is dependent on route URL or route values and that need to be implemented before the execution of route middleware can be done by accessing the route path from the current request context as below app.Use(async (context, next) => { if(context.Request.Path.Value.IndexOf("oldvehicle") != -1) { context.Response.Redirect("vehicle"); } else { await next(); } }); app.UseMvc(routes => { routes.MapRoute( name: "vehicleRoute", template: "vehicle", defaul

Asp.Net Core MVC Form Validation Techniques

Introduction: Form validations in any applications are like assures that a valid data is storing on servers. All programing frameworks have their own individual implementations for form validations. In Dotnet Core MVC application server-side validations carried on by the models with the help of Data Annotations and the client-side validations carried by the plugin jQuery Unobtrusive Validation. jQuery Unobtrusive Validation is a custom library developed by Microsoft based on the popular library  jQuery Validate . In this article, we are going to learn how the model validation and client-side validation works in Asp.Net Core MVC Application with sample examples. Getting Started: Let's create an Asp.Net Core MVC application project using preferred editors like Microsoft Visual Studio or Microsoft Visual Studio Code. Here I'm using Visual Studio. Let's create an MVC controller and name it as 'PersonController.cs' and add an action method as bel

.NET Core MVC Application File Upload To Physical Location With Buffered Technique

Buffering Technique In File Upload: The server will use its Memory(RAM) or Disk Storage to save the files on receiving a file upload request from the client.  Usage of Memory(RAM) or Disk depends on the number of file requests and the size of the file.  Any single buffered file exceeding 64KB is moved from Memory to a temp file on disk.  If an application receives heavy traffic of uploading files there might be a chance of out of Disk or RAM memory which leads to crash application. So this Buffer technique used for small files uploading. In the following article, we create a sample for the file uploading using .NET Core MVC application. Create The .NET Core MVC Project: Let's create a .NET Core MVC project, here for this sample I'm using Visual Studio Code as below.   Check the link to use the Visual Studio Code for .NET Core Application . IFormFile: Microsoft.AspNetCore.Http.IFormFile used for file upload with buffered technique. On uploading files f

Ionic Picker Sample Code In Angular

Introduction: Ionic Picker(ion-picker) is a popup slides up from the bottom of the device screen, which contains rows with selectable column separated items. The main building block of ion-picker as follows: PickerController PickerOptions PickerController: PickerController object helps in creating an ion-picker overlay. create(opts?: Opts): Promise<Overlay> PickerController create method helps in create the picker overlay with the picker options PickerOptions: PickerOptions is a configuration object used by PickerController to display ion-picker. Single Column Ionic Picker: single.item.picker.ts: import { Component } from "@angular/core"; import { PickerController } from "@ionic/angular"; import { PickerOptions } from "@ionic/core"; @Component({ selector: "single-column-picker", templateUrl:"single.item.picker.html" }) export class SingleItemPicker { animals: string[] = ["Tiger&quo

GraphQL API Integration In Asp.Net Core Application

Introduction: GraphQL is a query language for your API and a server-side runtime for executing queries by using a type system you define for your data. GraphQL can be integrated into any framework like ASP.NET, Java, NestJs, etc and it isn't tied to any specific database or storage engine and is instead backed by your existing code and data. How GraphQL API Different From Rest API: GraphQL exposes a single end-point or route for the entire application, regardless of its responses or actions. HTTP-POST is the only Http verb recommended by the GraphQL. The client applications (consumers of API) can give instructions to GraphQL API about what type of properties to be returned in the response. Building Blocks Of GraphQL API: The main building blocks of GraphQL API is Schemas and Types.  A 'Schema' in GrpahQL API describes the functionality available to the clients connect to API. Schema mostly consists of GraphQL Object Types, Queries, Mutations, etc. T

ASP.NET Core Web API Versioning

Introduction: An iteration and evolutionary changes of an ASP.NET Core Web API is handled by Versioning. Versioning of an API gives confidence to the clients which consumes API for a long time. Any changes or development of an API will be accessible using the new version and it won't cause issues to the clients consuming the old version of API. When To Use Versioning: Any API response changes. Developing an API by implementing testing levels like 'Alpha', 'Beta', and 'RC' versions before releasing Production. Deprecating an API which means API going to be removed or upgraded by a version within a short period. Versioning Types: Query String Versioning Url Path Versioning Media Type Versioning API Version Nuget: To Configure versioning to AspNet Core Web API Microsoft provided a library(Microsoft.AspNetCore.Mvc.Versioning). So to use the versioning library please install NuGet below.              Install-Package Microsoft.A

.Net Core HttpClient JSON Extension Methods Using System.Net.Http.Json Package

.Net Core 3.0 onwards Microsoft brought up a new package called System.Net.Http.Json. This new package provides JSON extension methods for HttpClient. These JSON extension methods will have a prebuild mechanism for serializing or deserializing response data or payload of HttpClient call. System.Net.Http.Json extension methods that are provided to HttpClient, few of them are mentioned below. GetFromJsonAsync PostAsJsonAsync PutAsJsonAsync ReadFromJsonAsync In this article, we understand System.Net.Http.Json package by implementing the HttpClient samples by with and without JSON extension methods and compare them. Create A .Net Core Web API Sample Application: Let's create a .Net Core sample Web API application, from this application we will consume another Web API by implementing HttpClient calls. We can create a Web API sample application using IDE like Visual Studio 2019(Supports .Net Core 3.0 plus) or  Visual Studio Code . Create A Typed Client: In .Net Core using the Http

Blazor Server CRUD Operations

Introduction: Blazor Server is a web framework to develop server-side single-page applications. Blazor is made up of components with the combinations on C#, Html, CSS.  Blazor Server is production-ready from the .Net Core 3.0.  Blazor Server Working Mechanism: Blazor Server is a very light-weight web development framework.  In Blazor Server, not all code gets downloaded to the client browsers. Blazor Server made of components these components can be a block of code or page with respective navigation.  Blazor server application communicates with the server with a SignalR background connection which is inbuilt functionality. Application click,  form submission, change events, application page navigation every operation is carried out by the SignalR connection by communicating with the server.  Blazor updates the Html DOM very gently on every data update without any overhead. Blazor Server application maintains a nice intelligent tree structure to update the required inform