angularangular2-observables

angular2 style guide - property with dollar sign?


Parent and children communicate via a service example from the official guide on Angular.io makes use of dollar signs in Observable stream names.

Notice missionAnnounced$ and missionConfirmed$ in the following example:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable()
export class MissionService {

  // Observable string sources
  private missionAnnouncedSource = new Subject<string>();
  private missionConfirmedSource = new Subject<string>();

  // Observable string streams
  missionAnnounced$ = this.missionAnnouncedSource.asObservable();
  missionConfirmed$ = this.missionConfirmedSource.asObservable();

  // Service message commands
  announceMission(mission: string) {
    this.missionAnnouncedSource.next(mission);
  }

  confirmMission(astronaut: string) {
    this.missionConfirmedSource.next(astronaut);
  }
}

Can anyone explain:


Solution

  • $ suffix (popularized by Cycle.js) is used to indicate that the variable is an Observable. It could make it to the official style guide too but it's not there yet

    Read more here : What does the suffixed dollar sign $ mean?

    The dollar sign $ suffixed to a name is a soft convention to indicate that the variable is a stream. It is a naming helper to indicate types.

    Suppose you have a stream of VNode depending on a stream of “name” strings

    const vdom$ = name$.map(name => h1(name));

    Notice that the function inside map takes name as an argument, while the stream is named name$. The naming convention indicates that name is the value being emitted by name$. In general, foobar$ emits foobar. Without this convention, if name$ would be named simply name, it would confuse readers about the types involved. Also, name$ is succinct compared to alternatives like nameStream, nameObservable, or nameObs. This convention can also be extended to arrays: use plurality to indicate the type is an array. Example: vdoms is an array of vdom but vdom$ is a stream of vdom.

    Update: Read more about the trailing “$” sign on Angular website here: https://angular.io/guide/observables#naming-conventions-for-observables

    Update April 2024: Updated the link