Sunday, August 23, 2020

Creating observable using Inline Arrow functions

In the previous post we created a separate function and passed it as a parameter to create an Observable. In this post we shall see on how to create an Observable using an inline arrow function.
In the below example we will create an Observable with an inline function which emits the current time, we use setInterval to emit a new value every 1 second.

The view template consumes this Observable and displays the current time in the View template, notice that the time in the UI gets refreshed every second, this is because whenever a new value is emitted from the Observer the asyncPipe automatically detects the change and refreshes the component.

app.component.ts

import { Component, OnInit } from '@angular/core';
import { Observable, Observer } from 'rxjs';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  currentTime$
  ngOnInit() {
    this.currentTime$ = new Observable<string>((observer: Observer<string>) => {
      setInterval(() => observer.next(new Date().toString()), 1000);     
    });
  }
}

app.component.html
<div>
  Current Time: {{ currentTime$ | async }} 
</div>

Output




Search Flipkart Products:
Flipkart.com

No comments: