Angular & RxJS

Why Angular?

Angular and JavaScript bring structure and consistency to web application development, and provides scalability and maintainability.

What is Angular?

Angular is an open source JavaScript framework. It is completely written in Typescript and primarily aimed to develop Single Page Applications. It uses HTML’s syntax to express your application’s components clearly. And also, it is maintained by Google. It is designed for web, desktop and mobile platform.

You do not need to rely on third party libraries to build dynamic applications with Angular. Angular uses HTML to define the UI of the application.HTML as compared to JavaScript is a less convoluted language. HTML is also a declarative and intuitive language.

With Angular you do not need any getter and setter functions. Since, it’s every object it uses is, POJO (Plain Old JavaScript Object), which enables object manipulation by providing all the conventional JavaScript functionalities. You can remove or add properties from the objects while also looping over these objects when required.

Features of Angular

Document Object Model (DOM)

DOM treats an XML or HTML document as a tree structure in which each node is an object representing a part of the object. Angular uses regular DOM. This will update the entire tree structure of HTML tags until it reaches the data to be updated. Consider about 100s update on the same HTML block is replaced for each request.

TypeScript

Angular is written in TypeScript. It is superset of JavaScript and offers excellent consistency. TypeScript is installed as an NPM package, and thus we can install with following command.

npm install –g typescript

Data binding

Data binding allows an Internet user to manipulate web page elements using a web browser. It is used for web pages that contain interactive components such as forms, calculators, tutorials and games. Angular uses two way binding.

Testing

Angular uses Jasmine to run various tests. The Jasmine framework allows various functionalities to write different kinds of test cases. Karma is the task runner for the tests.

Angular Architecture

Angular Architecture

Angular is a fully fledged MVC framework. Angular ensures easy development as it eliminates the need for unnecessary code. It has simplified MVC architecture which makes writing getters and setters needless.

Understanding in Angular

Directives

Directives are the building blocks of Angular applications. At the core a directive is a function that executes whenever the Angular compiler finds it in the DOM. Angular directives are used to extend the power of the HTML by giving it new syntax.

There are different types Angular directives are as follows.

Components — directives with a template

Attribute directives — Attributes directives manipulate the DOM by changing its behavior and appearance. We use attribute directives to apply conditional style to elements or dynamically change the behavior of a component according to a changing property.

Structural directivesStructural Angular directives are much less DOM friendly, as it can add or completely remove elements from the DOM. So when using these we have to be really careful since we are actually changing the HTML structure.

Modules

The Angular module known as ngModule and it helps to organize the application parts into cohesive blocks of functionality. Each block is focused on providing a specific functionality or a feature.

The Angular module must implement a specific feature. The Components, Directives, Services which implement such a feature and it will become part of that module.

Module design makes easy to maintain and reuse the code. Angular itself builds on the concepts of modules. The @angular/core is the main Angular module, which implements the Angular core functionality, low-level services and utilities. The features like Forms, HTTP and Routing are implemented as separate Feature modules such as FormsModule, HttpClientModule, RouterModule.

Decorators

Every type of decorator shares the same core functionality. The whole point of a decorator is to store metadata about a class, method or property. When you are providing metadata for that class that tells Angular, that we have a component, which has a specific configuration. There are four main types of decorators in Angular. Those are,

Class decorators — e.g:- @Component , @NgModule

Property decorators for properties inside classes — e.g:- @Input , @Output

Method decorators for methods inside the class — e.g:- @HostListner

Parameter decorators for parameters inside class constructors — e.g:- @Inject

Components

Every Angular component has a life cycle since life cycle is managed internally by Angular. According to the documentation

Angular creates it, renders it, creates and renders it’s children, checks it when it’s data-bound properties change, and destroys it before removing it from the DOM.

That is very simple description of the sequence of events that an Angular component’s life experiences. These events are called “Lifecycle Hooks”. We can use these lifecycle hooks to do something whenever one of these events occur.

https://angular.io/guide/lifecycle-hooks

Services

Angular services are singleton objects that get instantiated only once during the lifetime of an application. They could contain methods that maintain data throughout the life of an application. E.g -: Data does not get refreshed and is available all the time. The main objective of a service is to organize and share business logic, models, data and functions with different components of an Angular application.

An example of when to use services would be transfer data from one controller to another custom controller.

Guards

Whenever you do something before, it follows; the router and it pass the request in to the guard. Guard goes through this logic and see whether there is a liegemen request. Hence, it reveals how to protect the components or validations.

Routing

In Angular, routing plays a vital role since it is essentially used to create Single Page Applications (SPA). These applications are loaded just once, and new content is added dynamically. Applications like Google, Facebook, Twitter and Gmail are a few examples of SPA. The best advantage of SPA is that they provide an excellent user experience and you do not have to wait for pages to load, and by extension, this makes the SPA fast. We use route for navigations.

The Router-Outlet is a directive that is available from the router library where the router inserts the component that gets matched based on the current browser’s URL. You can add multiple outlets in your Angular application which enables you to implement advanced routing scenarios.

<router-outlet></router-outlet>

Any component that gets matched by the router will render it as a sibling of the Router outlet.

Dependency injection

Angular uses dependency injection design pattern, which makes it extremely efficient and makes a class independent of its dependencies. Dependency injection enables the creation of dependent objects outside of a class while providing those very objects to a class in numerous ways.

Consider two classes, A and B. Let’s assume that class A uses the objects of class B. Normally, in OOPS, an instance of class B is created so that class A can access the objects. Using DI, we move the creation and binding of the dependent objects outside of the class that depend on them.

Typically, there are three types of classes, they are:

1. Client Class — This is the dependent class, which depends on the service class.

2. Service Class — Class that provides the service to the client class.

3. Injector Class — Injects the service class object into the client class.

Types of Dependency Injection

There are three types of Dependency Injections in Angular, they are as follows:

1. Constructor injection: Here, it provides the dependencies through a class constructor.

2. Setter injection: The client uses a setter method into which the injector injects the dependency.

3. Interface injection: The dependency provides an injector method that will inject the dependency into any client passed to it. On the other hand, the clients must implement an interface that exposes a setter method that accepts the dependency.

Now that you know what DI is, and its types, let’s look at its advantages.

Advantages of Dependency Injection

Dependency injection offers some incredible advantages. Here are some of them

· Dependency Injection helps in Unit testing.

· Boilerplate code is reduced, as initializing of dependencies is done by the injector component.

· Extending the application becomes more manageable.

· It helps to enable loose coupling, which is essential in application programming.

Pipes and templates

Pipe is a technique. It can format our data and it transform template data directly. They help keep the component’s class lean of basic transformations. Pipes encapsulate data transformation logic.

In Angular there exists many ways to interact with data in the template HTML. Pipes can apply anywhere data is parsed into the template HTML. Pipes account for all transformations without adding onto the component class. Pipes are also chainable. You can integrate pipes one after the other to perform increasingly complex transformations. As specialized transformers, pipes are hardly trivial.

What is RxJS?

RxJs stands for Reactive Extensions for Java Script and its’ library gives us an implementation of observables for JavaScript. It composes asynchronous and event based programs by using observable sequences.

RxJs is like a conveyor belt. Let’s assume you have tea boxes in the conveyor belt and if the boxes are not properly packed it will take it out as an error. If the boxes are expected level it will put a label on that and once it shift it will turn over the belt. In RxJs, as a operator it will observed this conveyor belt.

RxJs need to subscribe and we need to give observer when we subscribe. There are multiple operators in RxJs and we can use any operators as we want. https://rxjs.dev/guide/overview

RxJs has some processing streams and it involves 3 steps.

1. Start (subscribe) — start emitting data

2. Observe the stream and do set of processes (observer)

- Get the next process — next()

-Handle if any error — error()

- End of operation — complete()

3. Stop (unsubscribe)

What is observe and observable?

Observer is the interface which is used to feed an observable source.

Conveyor belt

e.g-: let’s assume conveyor belt is the observer. Observable is for the consumer and it can be transformed and subscribed. It can create new observable with an observer. This will not emit data until we subscribed.

Streams are lazy

Yes. Streams are lazy. We need to subscribe to start either observer does not help. It is same as we manually start the conveyor belt to start tea boxes are moving. We need to pass the observer when subscribe so, observer will monitor every time item get emits.

Stopping Observer

There are multiple ways to observer. Some techniques are calling complete method and some does not. Those are…

* Call complete method — calling complete() method

*Use certain operators such as take(n) — calling complete() method

* Error — not calling complete() method

* Unsubscribe — not calling complete() method

How we can create observable?

There are two ways

Of — it will take the value use at once.

From — take the value one by one and emit.

Observable vs Subject

Observables are unicast by design and subject are multicast by design. With observable, each subscription receives the different values developed as unicast by design. But subject is similar to event emitter and it does not invoke for each subscription.

Find the best operator for your use case

When you start the conveyor belt make sure you need to observe it. So, RxJs, need to subscribe and there are some processors. Those are filter, map, tap, take.

Here, you can have an idea about how to use those operators.

Advantages of Angular

Angular framework is based on components which begin in the same style. For instance, each component places the code in a component class or defines a @component decorator. These components are small interface elements independent of each other and there are some advantages using Angular. Those are…

Reusability

The component based structure of Angular makes the components highly reusable across the app.

Simplified Unit Testing

Being independent of each other the components makes unit testing much easier.

Improved readability

Consistency in coding makes reading the code a piece of cake for new developers on an ongoing project, which adds to their productivity.

Ease of maintenance

Decoupled components are replaceable with better implementations.

Conclusion

In this article, I hope you will get a basic idea about the fundamentals of Angular and better understanding about RxJs and how we use operators according to our use case.

--

--

--

Software Engineer

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

How to create MERNG (Mongo DB, Express JS, React JS, Node JS and GraphQL) app PART 2

Processing of MERNG stack app

An introduction to Promises.

React — Advanced Useful Concepts

React JS and DRF — Introduction to React JS and Creating a hello world app with React JS

React Hooks

5 Badass Array Methods With Real Use Cases

Web Components

JavaScript Errors — Throw and Try to Catch

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
Poornima Vithanage

Poornima Vithanage

Software Engineer

More from Medium

Working with Angular

Angular

Reactive Forms in Angular

Pokedex using Angular and Bootstrap with PokeAPI