Uaxe is here! We recently launched a UI/UX Design Agency

Check Uaxe
Angular---Components--&-Observable
Aug
21
2019
21 Aug 2019

Angular – communicating between components with observable

What is an Angular Component :

The common definition of Components can be a small piece of code written in separate files so it can be reused whenever required in the building module. In angular components has decorators which can be defined as @component & it has properties like selectors, template, style, etc. Which is metadata specified in the processing component

Observables: 

Observables are not angular’s feature but it’s a feature of RXJS. Nowadays it’s used in angular & its purpose is to create a communication channel that can be subscribed by components to exchange data, while data gets an update then that data or message can be emitted to those components who subscribed to particular services. So observable can be used extensively in Angular. You will explore it in the given below example.

  • Observable extends class EventEmmitter.
  • Observable can be used to handle Services requests and responses.
  • Observable can be used as a service to use common data in multiple components.

Communicating between components Angular:

Generally, in angular there is a common way to transfer data from Parent component to child component there or vice-versa there are two decorators available @input and @output. But it gets complicated when it’s required to pass data through nested components or the component which is not part of a tree. In this case a handy solution is Observable of RXJS. 

Observable of RXJS

Observable concepts are like the ocean which can’t be covered in reading only instead need to dirty hands in a coding playground.

Observable has two main types Observable and a Subject . which can be used like Observable.subscribe() and Subject.next(). Observables technique is more preferable than other techniques due to even handling and asynchronous data loading. Observable has two methods

1. Observale.subscribe()
This method is used to subscribe to particular services or messages that are sent to an observable.

 2. Subject.next()
 This method is used to send messages to an observable than it will pass that message or data to the particular service or message subscriber of that observable.

Example: 

With this service, any component can subscribe to the service retriveMessage() method. And there are two more methods written over there for better understanding. broadCastMessage() to send messages from any components so broadcasted messages can be retrieved by its observable subscriber, same is for removeMessages() function. Service file will look like the code mentioned below.


import { Observable, Subject } from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class commonService {
    private subject = new Subject();

    broadCastMessage(message: string) {
        this.subject.next({ text: message });
    }

    removeMessages() {
        this.subject.next();
    }

    retriveMessage(): Observable {
        return this.subject.asObservable();
    }
}

app.component.ts file :
In this file, common services function has been used to retrieve messages whenever it’s sent by a user from the chat component. Which we will explore in the next code snippet.in this snippet, the retrieved message is getting pushed in chat array which will display in UI. If a clear function gets called then it will clear all messages from the chat.


import { Subscription } from 'rxjs';
import { Component, OnDestroy } from '@angular/core';
import { commonService } from './_services/index';
 
@Component({
    selector: 'app',
    templateUrl: 'app.component.html'
})
 
export class AppComponent implements OnDestroy {
    chat: any[] = [];
    subscription: Subscription;
 
    constructor(private commonService: commonService) {
        // subscribe to home component messages
        this.subscription = this.commonService.retriveMessage().subscribe(message => {
          if (message) {
            this.chat.push(message);
          } else {
            // clear messages when empty message received
            this.chat = [];
          }
        });
    }
 
    ngOnDestroy() {
        // unsubscribe to ensure no memory leaks
        this.subscription.unsubscribe();
    }
}

Next it’s time to create a send component.

sendMessage.component.ts file:

This send message component is used to send messages. It will be called broadcast.It will emit a message to a particular observable and retriverMessage() will receive a message. Or removeMessages() which will clear chat messages of the app component.


import { commonService } from '../_services/index';
import { Component } from '@angular/core';

@Component({ templateUrl: 'home.component.html' })
export class SendMessage{
  constructor(private commonService: commonService) { }
 
  broadCastMessage(): void {
      // send message to subscribers via observable subject
      this.messageService.broadCastMessage('Message from Home Component to App Component!');
   }
 
   removeMessages(): void {
     // clear messages
     this.messageService.removeMessages();
   }
}