codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Usage of Rxjs Observables in Angular

John Au-Yeung
codeburst
Published in
5 min readApr 19, 2020

--

Photo by Hans van Tol on Unsplash

Angular is a popular front-end framework made by Google. Like other popular front-end frameworks, it uses a component-based architecture to structure apps.

In this article, we’ll look at how Rxjs observables are used in Angular.

Transmitting Data Between Components

The EventEmitter class that’s used to send data from child to parent components uses observables to transmit the data,

When we call emit , the emitted value is passed to the next method to broadcast the emitted data to the parent component, which subscribes to the EventEmitter .

EventEmitter extends the Rxjs Subject class.

A simple example of emitting data from a child component to the parent would be the following:

app.module.ts :

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ChildComponent } from './child/child.component';
@NgModule({
declarations: [
AppComponent,
ChildComponent
],
imports: [
BrowserModule,
AppRoutingModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts :

import { Component } from '@angular/core';@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
emitted;
}

app.component.html :

<app-child (emitted)='emitted = $event'></app-child>
{{emitted}}

child.component.ts :

import { Component, OnInit, Output, EventEmitter } from '@angular/core';@Component({
selector: 'app-child',
templateUrl: './child.component.html',
styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
@Output() emitted = new EventEmitter();
constructor() { } ngOnInit() {
this.emitted.emit('foo')
}

--

--

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

No responses yet

Write a response