DuckFterminal
DuckFterminal

Reputation: 149

What does "$" in observable property mean?

I'm a newbie angular. I have a code example, but the creator does not explain to me the "$" what that mean, Can anyone tell me what blog$ and onDestroy$ here means? Or is that just how he named it? Thanks you!

blog-details.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { BlogService } from '../../services/blog.service';
import { Observable, Subject } from 'rxjs';
import { BlogItem } from '../../models/blog-item.model';
import { ActivatedRoute } from '@angular/router';
import { takeUntil } from 'rxjs/operators';

@Component({
  selector: 'app-blog-detail',
  templateUrl: './blog-detail.component.html',
  styleUrls: ['./blog-detail.component.scss']
})
export class BlogDetailComponent implements OnInit, OnDestroy {
  blog$: Observable<BlogItem>;
  private onDestroy$: Subject<boolean> = new Subject<boolean>();

  constructor(private readonly blogService: BlogService, private readonly route: ActivatedRoute) { }

  ngOnInit(): void {
    this.route.params.pipe(takeUntil(this.onDestroy$)).subscribe((params: any) => {
      const { id } = params;
      this.blog$ = this.blogService.getBlogDetail(id);
    });
  }

  ngOnDestroy(): void {
    this.onDestroy$.next(true);
    this.onDestroy$.complete();
  }
}

blog-detail.component.html

<p>blog-detail works!</p>
<div class="blog-detail" *ngIf="blog$ | async as blogDetail; else loading;">
    <div class="blog-detail-title">{{ blogDetail?.title }}</div>
    <div class="blog-detail-content">
      Content:
      <span>{{ blogDetail?.body }}</span>
    </div>
    <div>userId: {{ blogDetail?.userId }}</div>
</div>
<ng-template #loading>
  Loading...
</ng-template>

Upvotes: 3

Views: 1090

Answers (1)

Ben Bradshaw
Ben Bradshaw

Reputation: 364

The $ is a naming convention for observables and subjects. It is a way to mark that the variable is a "stream" rather than a plain object. It is an indicator that you can subscribe, pipe, and use rxjs operators with the variable. In Angular, it helps you remember that you can use the async pipe in the html.

Upvotes: 3

Related Questions