RxJS (Reactive Extensions for JavaScript) is a reactive programming library for composing asynchronous and event-based programs by using observable sequences. RxJS is a library that enables us to work with observables in Angular applications. Observables represent zero or more values returned either immediately or in the future. RxJS enables you to simplify asynchronous functions with much more flexibility and improved error handling than promises.
RxJS follows a stream-based approach. It provides functional and reactive programming patterns for working with events and streams of data. When you write complex applications you usually end up writing nested callbacks with multiple nesting levels. Promises and callbacks have this same nesting problem to some degree. A finer solution to the problem is the Observables which use the observer software pattern. An observable is an entity that emits (or publishes) multiple data values (streams of data) over time and asynchronously.
For the notion of streams to be useful to build a program, we need a way to create streams, subscribe to them, react to new values, and combine streams together to build new ones. Observables are used in Angular for this purpose along with better support of event handling, asynchronous programming, and handling multiple values. When you define an observable to publish some values for a consumer, the values are not emitted until you actually subscribe to the Observable. The consumer that subscribes to the observables keeps receiving values until the observer is completed or the consumer unsubscribes from the observable.
Angular relies on RxJS for some of its internal features. A few places in angular where reactive programming and observables are in use are in Event Emitters, Http, and reactive forms.
Custom events can be defined that send observable output data from a child to the parent component. The EventEmitter class is essentially an RxJS observable stream which powers component and directive outputs – extends the RxJS subject class. The subject then, in turn, extends both the RxJS observer and observable class. Thus we are able to operate on it and subscribe to it just like any other RxJS stream.
Example:
import { Component, OnInit, Input, Output, EventEmitter} from ‘@angular/core’;
@Component({
selector: ‘app-child’,
template: ` <p>count = {{count}}</p>\
<button (click)=’updateCount()’>update count </button> `})
export class ChildComponent implements OnInit {
constructor() { }
@Input() count: number;
@Output() countChange = new EventEmitter();
ngOnInit() {
}
updateCount() {
this.count = this.count + 1;
this.countChange.emit(this.count);
}}
In the above example, an instance of an EventEmitter called countChange was created, which will be emitted to the parent component on the click event of the button. The countChange event is emitted inside the function updateCount(). While emitting countChange event, the value of count property is also sent out of the component. EventEmitter is used in the directives and components to emit custom events either synchronously or asynchronously.
The Implementation of EventEmitter class:
class EventEmitter<T> extends Subject {
constructor(isAsync: boolean = false)
emit(value?: T) subscribe(generatorOrNext?: any, error?: any, complete?: any): Subscription }
Since EventEmitter class extends RxJS subject class, this means it is observable and can be multicasted to many observers.
In the AppComponent, the emitted event can be handled as shown below:
Import { Component } from ‘@angular/core’;
@Component({
selector: ‘app-root’,
template: `<h2>{{title}}</h2>
<app-child [count]=’count’ (countChange)=changeCount($event)></app-child> ` })
export class AppComponent {
count = 9;
changeCount(data) {
console.log(data);
} }
In Angular 1 Http was a promise based service. In Angular 2+, it is based on observables. The Angular’s HttpClient uses observables to return values from Http requests. For instance, http.get(‘/api’) returns an observable. This observable will not contain a value immediately, but it has a register method, where we can register a callback. This callback is called, once the result is available. Http requests are cancellable through the unsubscribe method.
Example:
constructor(private http: HttpClient) { }
this.http.get(‘https://…’).subscribe(value => {
// value contains the servers response (parsed from JSON by default)
});
}
Another place where the power of RxJS can be used is in forms. Reactive forms have properties that use observables to monitor form control values. Subscribing to an observable form-control property is a way of triggering application logic within the component class.
For Example:
@Component({
selector: ‘my-app’,
template: `
<form[formGroup]=”loginForm”(submit)=”submit$.next()”>
<label>Login:</label>
<input formControlName=”login” type=”text”>
<label>Password:</label>
<input formControlName=”password” type=”password”>
<button type=”submit”>Submit</button>
</form>`,})
export class AppComponent {
public loginForm: FormGroup
private submit$: Observable<any> = new Subject()
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.loginForm = this.formBuilder.group({
login: ”,
password: ”, })
this.submit$
.withLatestFrom(this.loginForm.valueChanges, (_, values) => values)
.subscribe(values => {
console.log(‘submitted values’, values)
}) }}
In the above example, there are a few additional blocks, the formControlName, the formBuilder.group, the [formGroup]. The formControlName is added to match names from templates to the appropriate fields in the controller. The formBuilder.group creates the form. The [formGroup] connects the template and the controller.
In the given example the form is submitted in a reactive way. The (submit) is put on the form which gives a stream of submitting events and a stream of values. All that remains is to combine these streams. The resulting stream will emit the current state of the fields when the form is submitted. The desired behavior can be achieved using the withLatestFrom operator of RxJS.
Angular exposes RxJS in a small but important number of places. As explained above Angular makes use of RxJS in EventEmitter, Http and Reactive Forms.
For a free consultation on IoT, Enterprise or Telecom Service, contact us at sales@thinkpalm.com
Author Bio:
Roshni Vidyadharan: Roshni works as a developer at ThinkPalm Technologies. Her hobbies include reading and keeping up with the latest technological trends.