angular2 style guide - property with dollar sign?
Asked Answered
M

4

324

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:

  • why $ is used? What's the reason behind this notation? Do I always need to use this for public properties?
  • public properties are used but not methods (e.g. missionAnnouncements(), missionConfirmations()) - again, is this a convention for Angular2 apps?
Mallette answered 7/6, 2016 at 6:7 Comment(0)
I
459

$ 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

Ionic answered 20/6, 2016 at 17:35 Comment(5)
Reference in the angular docs: angular.io/guide/rx-library#naming-conventions-for-observablesHannie
what about promises?Arrowhead
Is it only the observable or also subjects and other types of streams?Kindhearted
@Sarah: It was mentioned by @Rachel Diaz that Andre Staltz started this style. I found on his github that be uses this convention for behavior subjects as well: var modelItems$ = new Rx.BehaviorSubject(null);Myriammyriameter
This answer could be improved by including the reasoning from those links. Unfortunately the angular link no longer includes the naming convention section, so whatever point was there is lost.Bacchae
P
23

The $ naming paradigm originated with Andre Saltz and suggests pluralizing all variable names that contain observables or streams.

getAll(): Observable<Zone[]>{
    let zone$ = this.http
      .get(`${this.baseUrl}/zones`, {headers: this.getHeaders()})
      .map(mapZone);
      return zone$;
  }

Another approach is to pluralize variable names that contain observables or streams with a unicode character that matches the last letter of the word. This addresses the issue with words that aren't pluralized with an "s".

mouse$ vs mic€

Neither of these naming conventions are in the official Angular style guide. Usage of one or the other (or none) is entirely dependent on personal preference.

Poundfoolish answered 9/6, 2017 at 16:8 Comment(6)
cactu$ vs cactïBarreto
Nice reference! Also check out this article. What annoys me is finding an attempt to do this in my codebase (other co-workers) and getting it wrong, putting the suffix on the wrong variable or even worse starting the variable with it. I have seen people use this without consistency also, in that case it makes completely no sense. medium.com/@benlesh/…Lobachevsky
If you are to use it, I would reccomend following naming conventions like in this repo: github.com/bodiddlie/rxheroes/blob/master/app/effects/hero.ts And also doing it always or never. Be consistent for the observable god's sake.Lobachevsky
fish$ vs fish€$Ophelia
The naming convention for observables can now be found in the official documentation: angular.io/guide/rx-library#naming-conventions-for-observablesLamentation
Whoa! I never knew that the $ in observables was even related to the fact that it looks like an s.World
H
16

Update: https://angular.io/guide/rx-library#naming-conventions-for-observables

Because Angular applications are mostly written in TypeScript, you will typically know when a variable is an observable. Although the Angular framework does not enforce a naming convention for observables, you will often see observables named with a trailing “$” sign.

This can be useful when scanning through code and looking for observable values. Also, if you want a property to store the most recent value from an observable, it can be convenient to simply use the same name with or without the “$”.


Original:

I saw variables end with $ when reading the official hero tutorial:

<div id="search-component">
  <h4>Hero Search</h4>

  <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />

  <ul class="search-result">
    <li *ngFor="let hero of heroes$ | async" >
      <a routerLink="/detail/{{hero.id}}">
        {{hero.name}}
      </a>
    </li>
  </ul>
</div>

Look closely and you'll see that the *ngFor iterates over a list called heroes$, not heroes.

<li *ngFor="let hero of heroes$ | async" >

The $ is a convention that indicates heroes$ is an Observable, not an array.

Most cases are that we do not subscribe to those Observable variables in component. We usually use AsyncPipe to subscribe to the Observable variables automatically

I haven't found it in Style Guide since Angular5.1 has released yesterday(December 6th, 2017).

Horsehair answered 7/12, 2017 at 22:51 Comment(1)
From Angular 9 style guide heroes: Observable<Hero[]>;Sit
J
10

I haven't seen this $ in the style guide but I saw it being used frequently for public properties that refer to observables that can be subscribed to.

Jammiejammin answered 7/6, 2016 at 6:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.