liveBook · Manning

Subscribe

As explained in Pro Angular 16

The subscribe method registers callbacks or an observer with an observable to receive notifications for emitted values and other sequence events.

The subscribe method registers a function or observer with an Observable<T>, allowing code to react when values arrive instead of repeatedly checking whether asynchronous work has finished. An observable can produce a series of values, unlike a Promise, which represents a single result. section 10.5.1

Choose the subscription form according to the sequence events that need handling:

  • Pass a function when only emitted values matter; the function receives each new value. section 10.5.1
  • Pass an observer object when the subscription must handle next values, errors, and sequence completion. section 10.5.1
  • Subscribe during ngAfterContentInit to a QueryList changes observable when projected content can change. section 15.4.2
  • Account for asynchronous notifications: Angular change detection may need to run afterward through ChangeDetectorRef.detectChanges(). section 15.4.2

Displaying values from a ticker

A Ticker exposes an Observable<number> created with interval(500). A component subscribes with `this.ticker.value.subscribe(newValue => this.tickerValue = newValue);`, and its template displays `tickerValue`. Each emitted number updates the component without polling. section 10.5.1

Testing an output property

An EventEmitter output is an Observable object, so a unit test subscribes to the output before triggering mouseenter and mouseleave events. The received event is then used to verify the expected result. section 29.4.5

Table 10.5. The Observable<T> subscribe argument properties
Name
Description
next
This function is invoked when a new value is produced.
error
This function is invoked when an error occurs.
complete
This function is invoked when the sequence of values ends.

Use the callback-property table to distinguish value, error, and completion notifications accepted by subscribe. section 10.5.1

How Pro Angular 16 covers it

How deep it goes
Defines callback forms and demonstrates component, query-change, and testing uses, but does not cover subscription disposal.
Examples
Uses a 500-millisecond ticker, changing content queries, and mouse-event-driven EventEmitter tests.
What it assumes
Assumes JavaScript familiarity and introduces Observable<T> as a multi-value alternative to Promise-based asynchronous handling.
What you can do after
Apply it via RxJS and Angular to react to values, query changes, and component output events.
How it connects
Connects Observable, Promise, RxJS, interval, QueryList, Angular change detection, ChangeDetectorRef, and EventEmitter.

Also explained in

Compare how 3 books explain subscribe →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro Angular 16. The section links point to the parts of the book it draws on.