Skip to main content
InterviewHubPRO
Section Overview
Q49

Question 49 of 283

Part 2: HttpClient, RxJS Observables & Angular Elements (36 - 62)

17%
Angular Master (283 Qs)•Part 2: HttpClient, RxJS Observables & Angular Elements (36 - 62)

What are observable creation functions?

junior LevelMost AskedCode ExampleCLIRxJSHTTP & REST APIs

RxJS provides creation functions for the process of creating observables from promises, events, timers and Ajax requests. Let us explain each of them with an example:

  1. Create an observable from a promise
javascript
 import { from } from 'rxjs'; // from function
 const data = from(fetch('/api/endpoint')); //Created from Promise
 data.subscribe({
  next(response) { console.log(response); },
  error(err) { console.error('Error: ' + err); },
  complete() { console.log('Completed'); }
 });
  1. Create an observable that creates an AJAX request
javascript
 import { ajax } from 'rxjs/ajax'; // ajax function
 const apiData = ajax('/api/data'); // Created from AJAX request
 // Subscribe to create the request
 apiData.subscribe(res => console.log(res.status, res.response));
  1. Create an observable from a counter
javascript
 import { interval } from 'rxjs'; // interval function
 const secondsCounter = interval(1000); // Created from Counter value
 secondsCounter.subscribe(n =>
   console.log(`Counter value: ${n}`));
  1. Create an observable from an event
javascript
 import { fromEvent } from 'rxjs';
 const el = document.getElementById('custom-element');
 const mouseMoves = fromEvent(el, 'mousemove');
 const subscription = mouseMoves.subscribe((e: MouseEvent) => {
   console.log(`Coordnitaes of mouse pointer: ${e.clientX} * ${e.clientY}`);
   });