Weekly Webtips
Published in

Weekly Webtips

Tech: Reactive Programming in Angular

A deep dive into Reactive World

1. What is Reactive Programming?

Reactive programming is one of the most popular programming patterns in which the application asynchronously reacts to a data stream or change in states. This type of programming is very well known on front end development especially on building a single page application because it allows the app to respond to different types of inputs like user events, messages, server calls, etc. which do NOT usually happen in concurrent with the main flow.

We, as developers, often confuse the word “reactive” with “responsive” or use them interchangeably to describe a web page. In terms of front end development, the word “reactive” describes asynchronous behavior of the app while “responsive” is a web design that rearranges the looks and feels of the web elements in order to adapt to different screen sizes.

2. Observer Pattern

When talking about reactive programming, we cannot forget to mention the Observer pattern. This programming pattern was invented for the back end world but can be used for the front end as well. Since reactive programming mainly deals with state changes and subscriptions, understanding of this pattern will give you advantages to build a better reactive web page.

Observer pattern

In this pattern, there are 2 types of objects: Subject and Observer:

  • Subject is a class that contains states and has the ability to notify any state changes to its subscribers.
  • Subscriber is a class that gets attached to a particular Subject and has the ability to receive notification about state changes until it gets detached from the Subject.

3. Reactive Programming with Rxjs in Angular

If you are developers who use Angular framework to build web pages you ain’t strangers to RXJS. This library is maintained by an opensource team outside Angular and starts gaining more popularity among the Javascript community thanks to the usages of Observables and the ability to manipulate data stream before it reaches the end of “data pipe”. The library provides a lot of useful operators (map, switchMap, filters…) to help developers control what data they want to receive or display in the components and templates. More generally in terms of reactive programming, this library helps create Subject and allows Subscribers to watch and manipulate data stream from its Subject.

In this article, we won’t go deeply into how to use RXJS. However, if you want to learn more about the library you can find tons of tutorials on the internet or on the library’s website.

4. Practical Observable usages in Angular

Observables are being used heavily in Angular for sure. Here, we found 4 most infamous Angular APIs which they have Observable as their return types.

HttpClient

HttpClient is an awesome Angular package that helps developers communicate with remote services. It supports different types of HTTP requests like get, post, or put… When the request returns it comes back as an Observable type. The component or service needs to subscribe to this Observable to “unwrap” raw data inside.

import { HttpClient } from '@angular/common/http';export class MyService {  items: any[];  constructor(private http: HttpClient) {}  getItems() {
this.http.get<any[]>('remote url').subscribe(
resp => items = resp.data
);

}
}

Output’s EventEmitter

One of the most powerful features of Angular component is the ability to bind event property (Input) and react to those events (Output). The component’s Output has EventEmitter type which extends Observable’s Subject class so it obviously inherits all properties from Observable.

// child component
@Component({
selector: 'app-child'
})
export class ChildComponent { @Output()
closeClick = new EventEmitter();
onClick() {
this.closeClick.emit('some data');
}
}
// parent component
@Component({
selector: 'app-parent',
template: `<app-child></app-child>`
})
export class ParentComponent implements AfterViewInit { @ViewChild(ChildComponent)
childComp: ChildComponent;
activeItem: any; ngAfterViewInit() {

// receive emitted data from ChildComponent
this.childComp.closeClick.subscribe(
item => activeItem = item
);

}
}

Reactive Form’s ValueChanges

Reactive Form is another Angular package provided to developers out of the box. This package helps build forms programmatically and dynamically without the need to specify the form’s template first. In addition to that, it allows developers to subscribe to form values whenever changes occur. In order to do that we need to build a formGroup then call an API named valueChanges which, again, return as an Observable object. This is a very useful feature that allows us to react to the value changes and perform other tasks asynchronously.

formGroup: FormGroup;
message: string;
constructor(private formBuilder: FormBuilder) {} ngOnInit() {
this.formGroup = this.formBuilder.group({
message: ''
});
this.onChanges();
}
onChanges() {
this.myForm.valueChanges.subscribe(
val => this.message = val.message
);

}

Router Changes

Last but not least we can’t forget to mention another popular feature in Angular: Router. The way Observable being used in the Router is that it lets us subscribe to parameter changes in the URL and allow us to have custom logic to respond to those changes.

import { ActivatedRoute } from '@angular/router';selectedId: number;constructor(private route: ActivatedRoute) {}ngOnInit() {
this.route.paramMap.subscribe(
params => this.selectedId = Number(params.get('id'));
);

💡 Tip: All examples above (except for the first one) require developers to manually unsubscribe from the Observable when no longer needed to avoid memory leaks.

5. Final Thoughts

I hope this article gives you a nice introduction to reactive programming in general and all of the cool features from RXJS. If you have any questions about everything don’t hesitate to drop a comment in the Responses section.

6. Did you see my other posts?

--

--

--

Explore the world of web technologies through a series of tutorials

Recommended from Medium

Put your npm package on a Strict Diet

Generate Microservices Quickly With Yeoman

Event Listeners

I Graduated! What Now?

Create a Event in Kubernetes Using client-go

Leetcode 290. Word Pattern

Creating Blog site using Stackbit, GatsbyJS and DEV -6

5 Practical Applications of ‘this’ in JavaScript

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
Khoi Bui

Khoi Bui

Front End architect, opensource contributor and investment enthusiast. New content posted every week.

More from Medium

RxJS switchMap Operator

switchMap rxjx operator

How to Debug Angular Applications in Visual Studio Code

Swagger UI + Angular & ReactJS + Customization

Angular Framework