父级和子级通过Angular官方指南中的服务示例进行通信。io在Observable流名称中使用美元符号。

注意下面示例中的missionannounce $和missionConfirmed$:

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);
  }
}

谁能解释一下:

为什么使用$ ?这个符号背后的原因是什么?公共物品总是需要用这个吗? 使用公共属性,但不使用方法(例如missionannouncement (), missionconfirmation())——同样,这是Angular2应用程序的约定吗?


我没有在风格指南中看到这个$,但我看到它经常用于引用可订阅的可观察对象的公共属性。

$后缀(由Cycle.js普及)用于指示变量是一个Observable。 它可能也会出现在官方的风格指南中,但目前还没有

在这里阅读更多:带后缀的美元符号$是什么意思?

更新: 在Angular网站上阅读更多关于尾随“$”符号的信息: https://angular.io/guide/rx-library#naming-conventions-for-observables

$命名范式起源于Andre Saltz,并建议将所有包含可观察对象或流的变量名复数。

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

另一种方法是将包含可观察对象或流的变量名用与单词的最后一个字母匹配的unicode字符复数。这个方法解决了单词中没有复数形式的“s”的问题。

mouse$ vs mic€

这些命名约定都没有出现在Angular的官方风格指南中。使用一种或另一种(或没有)完全取决于个人喜好。

更新: 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 “$”.


原:

在阅读官方英雄教程时,我看到变量以$结尾:

<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>

仔细观察,你会发现*ngFor迭代的是一个名为heroes$的列表,而不是heroes。

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

$是一个约定,表示heroes$是一个Observable,而不是数组。

大多数情况下,我们不订阅组件中的那些可观察变量。我们通常使用AsyncPipe自动订阅Observable变量

自从昨天(2017年12月6日)Angular5.1发布以来,我就没有在风格指南中找到它。