0 votes
in Angular by

What is subscribing?

1 Answer

0 votes
by

An Observable instance begins publishing values only when someone subscribes to it. So you need to subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.

Let's take an example of creating and subscribing to a simple observable, with an observer that logs the received message to the console.

// Creates an observable sequence of 5 integers, starting from 1

const source = range(1, 5);

// Create observer object

const myObserver = {

  next: x => console.log('Observer got a next value: ' + x),

  error: err => console.error('Observer got an error: ' + err),

  complete: () => console.log('Observer got a complete notification'),

};

// Execute with the observer object and Prints out each item

source.subscribe(myObserver);

// => Observer got a next value: 1

// => Observer got a next value: 2

// => Observer got a next value: 3

// => Observer got a next value: 4

// => Observer got a next value: 5

// => Observer got a complete notification

...