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

  1. api/Products is missing can you share same repo

    ReplyDelete
    Replies
    1. It is my local running .net core api. It is not under angular reposity

      Delete
  2. Hi Naveen, Excellent article and youtube video. Got stuck on implementing it though. I get the following run-time error in the console 'httpUrlGenerator.registerHttpResourceUrls is not a function'.

    Thanks.

    ReplyDelete
  3. Just as an FYI. I'm using strict mode. Not sure whether that would cause the issue.

    ReplyDelete
  4. I tried to get this to run locally, but without a backend API working, it fails. I think you should either post the code to run the API locally or make a note at the beginning of this article that this is not meant to be run on your local machine because there is no functioning API available.

    ReplyDelete

Post a Comment

Popular posts from this blog

Angular 14 Reactive Forms Example

In this article, we will explore the Angular(14) reactive forms with an example. Reactive Forms: Angular reactive forms support model-driven techniques to handle the form's input values. The reactive forms state is immutable, any form filed change creates a new state for the form. Reactive forms are built around observable streams, where form inputs and values are provided as streams of input values, which can be accessed synchronously. Some key notations that involve in reactive forms are like: FormControl - each input element in the form is 'FormControl'. The 'FormControl' tracks the value and validation status of form fields. FormGroup - Track the value and validate the state of the group of 'FormControl'. FormBuilder - Angular service which can be used to create the 'FormGroup' or FormControl instance quickly. Form Array - That can hold infinite form control, this helps to create dynamic forms. Create An Angular(14) Application: Let'

.NET 7 Web API CRUD Using Entity Framework Core

In this article, we are going to implement a sample .NET 7 Web API CRUD using the Entity Framework Core. Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, and desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains programming functions that can be requested via HTTP calls either to fetch or update data for their respective clients. Some of the Key Characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build the REST full services. Install The SQL Server And SQL Management Studio: Let's install the SQL server on our l

ReactJS(v18) JWT Authentication Using HTTP Only Cookie

In this article, we will implement the ReactJS application authentication using the HTTP-only cookie. HTTP Only Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing the JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-ONly cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use the authentication with HTTP-only JWT cookie then we no need to implement the custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To authenticate our client application with JWT HTTP-only cookie, I developed a NetJS(which is a node) Mock API. Check the GitHub link and read the document on G

.NET6 Web API CRUD Operation With Entity Framework Core

In this article, we are going to do a small demo on AspNetCore 6 Web API CRUD operations. What Is Web API: Web API is a framework for building HTTP services that can be accessed from any client like browser, mobile devices, desktop apps. In simple terminology API(Application Programming Interface) means an interface module that contains a programming function that can be requested via HTTP calls to save or fetch the data for their respective clients. Some of the key characteristics of API: Supports HTTP verbs like 'GET', 'POST', 'PUT', 'DELETE', etc. Supports default responses like 'XML' and 'JSON'. Also can define custom responses. Supports self-hosting or individual hosting, so that all different kinds of apps can consume it. Authentication and Authorization are easy to implement. The ideal platform to build REST full services. Create A .NET6 Web API Application: Let's create a .Net6 Web API sample application to accomplish our

Angular 14 State Management CRUD Example With NgRx(14)

In this article, we are going to implement the Angular(14) state management CRUD example with NgRx(14) NgRx Store For State Management: In an angular application to share consistent data between multiple components, we use NgRx state management. Using NgRx state helps to avoid unwanted API calls, easy to maintain consistent data, etc. The main building blocks for the NgRx store are: Actions - NgRx actions represents event to trigger the reducers to save the data into the stores. Reducer - Reducer's pure function, which is used to create a new state on data change. Store - The store is the model or entity that holds the data. Selector - Selector to fetch the slices of data from the store to angular components. Effects - Effects deals with external network calls like API. The effect gets executed based the action performed Ngrx State Management flow: The angular component needs data for binding.  So angular component calls an action that is responsible for invoking the API call.  Aft

Angular 14 Crud Example

In this article, we will implement CRUD operation in the Angular 14 application. Angular: Angular is a framework that can be used to build a single-page application. Angular applications are built with components that make our code simple and clean. Angular components compose of 3 files like TypeScript File(*.ts), Html File(*.html), CSS File(*.cs) Components typescript file and HTML file support 2-way binding which means data flow is bi-directional Component typescript file listens for all HTML events from the HTML file. Create Angular(14) Application: Let's create an Angular(14) application to begin our sample. Make sure to install the Angular CLI tool into our local machine because it provides easy CLI commands to play with the angular application. Command To Install Angular CLI npm install -g @angular/cli Run the below command to create the angular application. Command To Create Angular Application ng new name_of_your_app Note: While creating the app, you will see a noti

Unit Testing Asp.NetCore Web API Using xUnit[.NET6]

In this article, we are going to write test cases to an Asp.NetCore Web API(.NET6) application using the xUnit. xUnit For .NET: The xUnit for .Net is a free, open-source, community-focused unit testing tool for .NET applications. By default .Net also provides a xUnit project template to implement test cases. Unit test cases build upon the 'AAA' formula that means 'Arrange', 'Act' and 'Assert' Arrange - Declaring variables, objects, instantiating mocks, etc. Act - Calling or invoking the method that needs to be tested. Assert - The assert ensures that code behaves as expected means yielding expected output. Create An API And Unit Test Projects: Let's create a .Net6 Web API and xUnit sample applications to accomplish our demo. We can use either Visual Studio 2022 or Visual Studio Code(using .NET CLI commands) to create any.Net6 application. For this demo, I'm using the 'Visual Studio Code'(using the .NET CLI command) editor. Create a fo

Part-1 Angular JWT Authentication Using HTTP Only Cookie[Angular V13]

In this article, we are going to implement a sample angular application authentication using HTTP only cookie that contains a JWT token. HTTP Only JWT Cookie: In a SPA(Single Page Application) Authentication JWT token either can be stored in browser 'LocalStorage' or in 'Cookie'. Storing JWT token inside of the cookie then the cookie should be HTTP Only. The HTTP-Only cookie nature is that it will be only accessible by the server application. Client apps like javascript-based apps can't access the HTTP-Only cookie. So if we use authentication with HTTP only JWT cookie then we no need to implement custom logic like adding authorization header or storing token data, etc at our client application. Because once the user authenticated cookie will be automatically sent to the server by the browser on every API call. Authentication API: To implement JWT cookie authentication we need to set up an API. For that, I had created a mock authentication API(Using the NestJS Se

ReactJS(v18) Authentication With JWT AccessToken And Refresh Token

In this article, we are going to do ReactJS(v18) application authentication using the JWT Access Token and Refresh Token. JSON Web Token(JWT): JSON Web Token is a digitally signed and secured token for user validation. The JWT is constructed with 3 important parts: Header Payload Signature Create ReactJS Application: Let's create a ReactJS application to accomplish our demo. npx create-react-app name-of-your-app Configure React Bootstrap Library: Let's install the React Bootstrap library npm install react-bootstrap bootstrap Now add the bootstrap CSS reference in 'index.js'. src/index.js: import 'bootstrap/dist/css/bootstrap.min.css' Create A React Component 'Layout': Let's add a React component like 'Layout' in 'components/shared' folders(new folders). src/components/shared/Layout.js: import Navbar from "react-bootstrap/Navbar"; import { Container } from "react-bootstrap"; import Nav from "react-boot

A Small Guide On NestJS Queues

NestJS Application Queues helps to deal with application scaling and performance challenges. When To Use Queues?: API request that mostly involves in time taking operations like CPU bound operation, doing them synchronously which will result in thread blocking. So to avoid these issues, it is an appropriate way to make the CPU-bound operation separate background job.  In nestjs one of the best solutions for these kinds of tasks is to implement the Queues. For queueing mechanism in the nestjs application most recommended library is '@nestjs/bull'(Bull is nodejs queue library). The 'Bull' depends on Redis cache for data storage like a job. So in this queueing technique, we will create services like 'Producer' and 'Consumer'. The 'Producer' is used to push our jobs into the Redis stores. The consumer will read those jobs(eg: CPU Bound Operations) and process them. So by using this queues technique user requests processed very fastly because actually