Aug
21
2019

What is an Angular Component : 

Components are like the basic building block in an Angular Application Development. Components are defined using the @component decorator. A component has a selector, template, style and other properties, using which it specifies the metadata required to process the component.

Observables :

An exciting new feature used with Angular is the Observable. This isn’t an Angular specific feature, but rather a proposed standard for managing async data that will be included in the release of ES7. Observables open up a continuous channel of communication in which multiple values of data can be emitted over time. From this we get a pattern of dealing with data by using array-like operations to parse, modify and maintain data. Angular uses observables extensively – you’ll see them in the HTTP service and the event system.

  • The EventEmitter class extends Observable.
  • The HTTP module uses observables to handle AJAX requests and responses.
  • The Router and Forms modules use observables to listen for and respond to user-input events.

communicating between components with observable : 
The way to communicate between components is to use an Observable and a Subject (which is a type of observable), I won’t go too much into the details about how observables work here since it’s a big subject, but in a nutshell there are two methods that we’re interested in: Observable.subscribe() and Subject.next().

1. Observable.subscribe()
The observable subscribe method is used by angular components to subscribe to messages that are sent to an observable.

2. Subject.next()
The subject next method is used to send messages to an observable which are then sent to all angular components that are subscribers of that observable.

Example: Message Service
With the message service you can subscribe to new messages in any component with getMessage() method, send messages from any component with the sendMessage(message: string) method, and clear messages from any component with the clearMessages() method.
The clearMessages() method actually just sends an empty message by calling this.subject.next() without any arguments, the logic to clear the messages when an empty message is received is in the app component.
Example :  stackblitz.com Example

Service File :

import { Observable, Subject } from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable({ providedIn: 'root' })
export class MessageService {
    private subject = new Subject();
 
    sendMessage(message: string) {
        this.subject.next({ text: message });
    }
 
    clearMessages() {
        this.subject.next();
    }
 
    getMessage(): Observable {
        return this.subject.asObservable();
    }
}

app.component.ts file :
The app component uses the message service to subscribe to new messages and push them into the messages array which is displayed in the app component template. If an empty message is received then the messages array is cleared which automatically removes the messages from the UI.


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

New Home Component create :

home.component.ts file :
The home component uses the message service to send messages to the app component.


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

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