How ngrx will save your bandwidth and development process.
In this article we’ll dive into RxJS-powered state management for Angular applications, inspired by Redux. How this approach can improve medium- and large-scale application development process, what are the benefits of using ngrx and what are the core principles behind it.
What’s So Hard About Managing the State?
Let’s take a look at the image below.
This is just a typical application. It looks relatively simple, just a few components and services, but as you can see there are a lot of connections. We’ve got a lot of things going on, and the state of our application is actually edited and queried from all over our code. That can lead to issues, because, as our application grows, maintenance and always knowing where new state is added to it, and which services of our app could potentially override existing state, can be difficult. It can be hard to keep track of where the state gets changed and queried in our application. Of course, you can get rid of storing state in the service and call back-end for new data every time when a component is initialized, but it will cost you a lot of bandwidth.
Real Life Problem
Stories on software engineering straight to your inbox
At nexocode we are working on a big Angular application, which has a lot of components and data which is changing all the time. We also deliver our data in real-time connection and in many components we are using same data in particular cases.
For example, we have a component that’s listing many documents, there is also a details page of each document and statistics pages where we need to count some partial data from some documents. Each of them belongs to a user who also has list, details, and statistics. There are also related reviewers and admins, so there are many connections.
So, as you can see, it’s hard to keep track of the app state and we always have to know where our state will change and where we should update it.
Redux to the Rescue!
In the Redux approach you have one central store in your application. So, one central place where you can manage all your application state, the single source of truth. Let’s take a closer look at the image:
Your components and services are now calling to one central store. You don’t have to worry about what service you have to provide in a component, or if you should update data only in one service or more. All will be covered by ngrx, so your code will be much cleaner and more readable. You can get rid of all if-statements in your services where you had to check if the data is already loaded or not. Also, if you didn’t store your data before, you will save a lot of bandwidth.
Your components and services are now calling to one central store. You don’t have to worry about what service you have to provide in a component, or if you should update data only in one service, or more. All will be covered by ngrx, so your code will be much cleaner and more readable. You can get rid of all if statements in your services where you had to check if the data is already loaded or not. Also, if you didn’t store your data before, you will save a lot of bandwidth.
Now you’re able to dispatch action and store data via ngrx, you can do it by simply writing:
import { Store } from '@ngrx/store';
import * as fromStore from '../../store';
export class MyComponent(){
constructor(private store: Store<fromStore.UsersState>) { }
loadUsers(){
this.store.dispatch(new fromStore.LoadUsers());
}
}
Adding Effects
@ngrx/effects provides an API to model event sources as actions. Effects:
Listen for actions dispatched from @ngrx/store.
Isolate side effects from components, allowing for more pure components that select state and dispatch actions.
Provide
new sources of actions to reduce state based on external interactions such as network requests, WebSocket messages and time-based events.
Here is a simple example of using effects in our app:
As you can see, anytime you dispatch LOAD_USERS action, this effect will be triggered and dispatch new action at the end. Remember that effects are Observables, so you have to always return an Observable. Also, at the end you have to dispatch a new action. You can disable it by adding { dispatch: false } to the Effect decorator, for example when you want to log out a user.
Selectors
The last thing about ngrx is selectors. Selectors are pure functions that take slices of state as arguments and return some state data that we can pass to our components. Selectors will return an Observable<T> as a value, so you can use it with async pipe or subscribe for value changes, example below:
this.users$ = this.store.select(fromStore.getAllUsers);
<ul>
<li *ngFor="let user of $users | async">...</li>
</ul>
this.subscription$ = this.store.select(fromStore.getAllUsers).subscribe(users => {
... // do something with data
this.users = users // just an example
}
//on destroy
this.subscription$.unsubscribe();
<ul>
<li *ngFor="let user of users">...</li>
</ul>
Remember that when you use subscription, you have to unsubscribe. When you use async approach, Angular will handle unsubscribe for you. Creating new selectors is very simple, a few examples below:
Wojciech is a Javascript developer with many years of experience. He's always striving to find new ways to evolve and expand his knowledge to be the best he can for himself and others. One thing that sets him apart from other frontend developers is his understanding of backend nature, which he gained through working on many projects as an experienced professional. Wojciech has experience in various frameworks and technologies, giving him a uniquely diverse skill set. Wojciech brings a whole new dimension to his work by being able to contribute significant project improvements.
What goes on behind the scenes in our engineering team? How do we solve large-scale technical challenges? How do we ensure our applications run smoothly? How do we perform testing and strive for clean code?
Follow our article series to get insight into our developers' current work and learn from their experience. Expect to see technical details, architecture discussions, reviews on libraries and tools we use, best practices on software quality, and maybe even some fail stories.
In the interests of your safety and to implement the principle of lawful, reliable and transparent
processing of your personal data when using our services, we developed this document called the
Privacy Policy. This document regulates the processing and protection of Users’ personal data in
connection with their use of the Website and has been prepared by Nexocode.
To ensure the protection of Users' personal data, Nexocode applies appropriate organizational and
technical solutions to prevent privacy breaches. Nexocode implements measures to ensure security at
the level which ensures compliance with applicable Polish and European laws such as:
Regulation (EU) 2016/679 of the European Parliament and of the Council of 27 April 2016 on
the protection of natural persons with regard to the processing of personal data and on the free
movement of such data, and repealing Directive 95/46/EC (General Data Protection Regulation)
(published in the Official Journal of the European Union L 119, p 1);
Act of 10 May 2018 on personal data protection (published in the Journal of Laws of 2018, item
1000);
Act of 18 July 2002 on providing services by electronic means;
Telecommunications Law of 16 July 2004.
The Website is secured by the SSL protocol, which provides secure data transmission on the Internet.
1. Definitions
User – a person that uses the Website, i.e. a natural person with full legal capacity, a legal
person, or an organizational unit which is not a legal person to which specific provisions grant
legal capacity.
Nexocode – NEXOCODE sp. z o.o. with its registered office in Kraków, ul. Wadowicka 7, 30-347 Kraków, entered into the Register of Entrepreneurs of the National Court
Register kept by the District Court for Kraków-Śródmieście in Kraków, 11th Commercial Department
of the National Court Register, under the KRS number: 0000686992, NIP: 6762533324.
Website – website run by Nexocode, at the URL: nexocode.com whose content is available to
authorized persons.
Cookies – small files saved by the server on the User's computer, which the server can read when
when the website is accessed from the computer.
SSL protocol – a special standard for transmitting data on the Internet which unlike ordinary
methods of data transmission encrypts data transmission.
System log – the information that the User's computer transmits to the server which may contain
various data (e.g. the user’s IP number), allowing to determine the approximate location where
the connection came from.
IP address – individual number which is usually assigned to every computer connected to the
Internet. The IP number can be permanently associated with the computer (static) or assigned to
a given connection (dynamic).
GDPR – Regulation 2016/679 of the European Parliament and of the Council of 27 April 2016 on the
protection of individuals regarding the processing of personal data and onthe free transmission
of such data, repealing Directive 95/46 / EC (General Data Protection Regulation).
Personal data – information about an identified or identifiable natural person ("data subject").
An identifiable natural person is a person who can be directly or indirectly identified, in
particular on the basis of identifiers such as name, identification number, location data,
online identifiers or one or more specific factors determining the physical, physiological,
genetic, mental, economic, cultural or social identity of a natural person.
Processing – any operations performed on personal data, such as collecting, recording, storing,
developing, modifying, sharing, and deleting, especially when performed in IT systems.
2. Cookies
The Website is secured by the SSL protocol, which provides secure data transmission on the Internet.
The Website, in accordance with art. 173 of the Telecommunications Act of 16 July 2004 of the
Republic of Poland, uses Cookies, i.e. data, in particular text files, stored on the User's end
device. Cookies are used to:
improve user experience and facilitate navigation on the site;
help to identify returning Users who access the website using the device on which Cookies were
saved;
creating statistics which help to understand how the Users use websites, which allows to improve
their structure and content;
adjusting the content of the Website pages to specific User’s preferences and optimizing the
websites website experience to the each User's individual needs.
Cookies usually contain the name of the website from which they originate, their storage time on the
end device and a unique number. On our Website, we use the following types of Cookies:
"Session" – cookie files stored on the User's end device until the Uses logs out, leaves the
website or turns off the web browser;
"Persistent" – cookie files stored on the User's end device for the time specified in the Cookie
file parameters or until they are deleted by the User;
"Performance" – cookies used specifically for gathering data on how visitors use a website to
measure the performance of a website;
"Strictly necessary" – essential for browsing the website and using its features, such as
accessing secure areas of the site;
"Functional" – cookies enabling remembering the settings selected by the User and personalizing
the User interface;
"First-party" – cookies stored by the Website;
"Third-party" – cookies derived from a website other than the Website;
"Facebook cookies" – You should read Facebook cookies policy: www.facebook.com
"Other Google cookies" – Refer to Google cookie policy: google.com
3. How System Logs work on the Website
User's activity on the Website, including the User’s Personal Data, is recorded in System Logs. The
information collected in the Logs is processed primarily for purposes related to the provision of
services, i.e. for the purposes of:
analytics – to improve the quality of services provided by us as part of the Website and adapt
its functionalities to the needs of the Users. The legal basis for processing in this case is
the legitimate interest of Nexocode consisting in analyzing Users' activities and their
preferences;
fraud detection, identification and countering threats to stability and correct operation of the
Website.
4. Cookie mechanism on the Website
Our site uses basic cookies that facilitate the use of its resources. Cookies contain useful
information
and are stored on the User's computer – our server can read them when connecting to this computer
again.
Most web browsers allow cookies to be stored on the User's end device by default. Each User can
change
their Cookie settings in the web browser settings menu:
Google ChromeOpen the menu (click the three-dot icon in the upper right corner), Settings >
Advanced. In
the "Privacy and security" section, click the Content Settings button. In the "Cookies and site
date"
section you can change the following Cookie settings:
Deleting cookies,
Blocking cookies by default,
Default permission for cookies,
Saving Cookies and website data by default and clearing them when the browser is closed,
Specifying exceptions for Cookies for specific websites or domains
Internet Explorer 6.0 and 7.0
From the browser menu (upper right corner): Tools > Internet Options >
Privacy, click the Sites button. Use the slider to set the desired level, confirm the change with
the OK
button.
Mozilla Firefox
browser menu: Tools > Options > Privacy and security. Activate the “Custom” field.
From
there, you can check a relevant field to decide whether or not to accept cookies.
Opera
Open the browser’s settings menu: Go to the Advanced section > Site Settings > Cookies and site
data. From there, adjust the setting: Allow sites to save and read cookie data
Safari
In the Safari drop-down menu, select Preferences and click the Security icon.From there,
select
the desired security level in the "Accept cookies" area.
Disabling Cookies in your browser does not deprive you of access to the resources of the Website.
Web
browsers, by default, allow storing Cookies on the User's end device. Website Users can freely
adjust
cookie settings. The web browser allows you to delete cookies. It is also possible to automatically
block cookies. Detailed information on this subject is provided in the help or documentation of the
specific web browser used by the User. The User can decide not to receive Cookies by changing
browser
settings. However, disabling Cookies necessary for authentication, security or remembering User
preferences may impact user experience, or even make the Website unusable.
5. Additional information
External links may be placed on the Website enabling Users to directly reach other website. Also,
while
using the Website, cookies may also be placed on the User’s device from other entities, in
particular
from third parties such as Google, in order to enable the use the functionalities of the Website
integrated with these third parties. Each of such providers sets out the rules for the use of
cookies in
their privacy policy, so for security reasons we recommend that you read the privacy policy document
before using these pages.
We reserve the right to change this privacy policy at any time by publishing an updated version on
our
Website. After making the change, the privacy policy will be published on the page with a new date.
For
more information on the conditions of providing services, in particular the rules of using the
Website,
contracting, as well as the conditions of accessing content and using the Website, please refer to
the
the Website’s Terms and Conditions.
Nexocode Team
Want to be a part of our engineering team?
Join our teal organization and work on challenging projects.