How to use @ngrx/data in 3 Steps

That was the time when you had to create the actions and reducer for doing multiple operations, Thanks to ngrx team for creating ngrx/data. This is an awesome l̶i̶b̶r̶a̶r̶y̶ boilerplate, using which you don’t have to create services, actions and, reducers (depends on the requirements).

For a basic application, we can directly start with the ngrx/data.

Why should we use ngrx/data?

This library gives multiple features, which are as follows:

  1. No need to create anything, Ohh by anything I mean actions, reducers, effects, selectors and blah blah of course.

and some more…

How to use it?

Time for some action…

Image for post
Image for post
Source: Google Images

Step 1: Install the libraries.

npm install @ngrx/effects @ngrx/entity @ngrx/store @ngrx/store-devtools @ngrx/data

Step 2: Create a Store and Module

import { NgModule } from '@angular/core';
import { EntityDataModule } from '@ngrx/data';
import { EffectsModule } from '@ngrx/effects';
import { StoreModule } from '@ngrx/store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { entityMetadata } from './zeus-store.meta';
import { DocumentService, SelectedDocumentService, SelectedPageService } from './zeus-store.service';
@NgModule({
imports: [
StoreModule.forRoot({}, {}),
EffectsModule.forRoot([]),
EntityDataModule.forRoot({ entityMetadata }),
StoreDevtoolsModule.instrument(),
],
});
export class EmployeeStoreModule {}

In the above step, we haven't done anything special except importing the modules from libraries.

  • Create Store-meta : Create a file with name whatever you want! But I’ll prefer store-meta since it contains the metadata related to store
export const entityMetadata: EntityMetadataMap = { }

Now, what the hell is this:@?

This is an object which will have mapper for entity store, still didn’t get it? In simple words this object will have an object with the name of the entity for example employee and that object will have some other definitions and functions like :

  • entityName — The entityName of the type is the only required metadata property. It's the unique key of the entity type's metadata in the cache.

Example:

export function getUserId(user: JWTUser): string {
return user.sub;
}
export const entityMetadata: EntityMetadataMap = {
Employee: {
entityName: 'Employee',
selectId: getUserId,
...
},
  • Create a service

This service will implement your Http methods and will add the default data to the store.

@Injectable({providedIn: 'root'})export class EmployeeService extends EntityCollectionServiceBase<Employee> {constructor(serviceElementsFactory:     EntityCollectionServiceElementsFactory) {
super('Employee', serviceElementsFactory);
}
}
  • Implement Default Data Service (configuration for overriding the HTTP default setter)
const defaultDataServiceConfig: DefaultDataServiceConfig = { 
root: 'https://my-api-domain.com:8000/api/v1',
timeout: 3000, // request timeout
}
// add this in your module as well
providers: [
{ provide: DefaultDataServiceConfig, useValue: defaultDataServiceConfig }
]

Step 3: Use it

And… we are at step 3 now, I know its more than 3 steps but that's what we call micro-steps :D

Now let’s how can we use the service.

constructor(private service: EmployeeService) {    this.service.getById('employeeId').subscribe(response => {
// do what ever you want to do with data...
})
}

Wait… what? but I never created the getById method in my employee service. Here comes the magic our employee service is extending a class “EntityCollectionServiceBase” this is the class that has all the boilerplate for us and from there only you are getting all the method. The default service, that we implemented, has an API endpoint so the final URL will be.

https://my-api-domain.com:8000/api/v1/entiyNamein our case it will behttps://my-api-domain.com:8000/api/v1/Employees (adding s by default by default service to make it plural)

After calling your getById method

  1. It will hit the API

Boom… and it's done.

But You know what? I don’t want to use this default HTTP service and instead, want to have all HTTP control in my hands? What should I do? hmm… let’s see

On exploring more I found my employee service has some inbuilt methods like addOneToCache and some others hence I experimented with it and found the result. Example :

getEmployeeById() {
return this.httpService.get('https:someurl.com/employee/1').pipe(map((response)=> {
this.addOneToCache(response);
return of(response);
}));
}

and it is also done… :)

Well if you want to explore more about methods that are available, you can always go to website https://ngrx.io/guide/data/entity-dataservice

I hope you’ll really like my work… and by the way, you can clap maximum of 50 times :D

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store