subject with injection angular code example

Example 1: subject in angular 8

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

@Injectable({ providedIn: 'root' })
export class MessageService {
    private subject = new Subject<any>();

    sendMessage(message: string) {
        this.subject.next({ text: message });
    }

    clearMessages() {
        this.subject.next();
    }

    getMessage(): Observable<any> {
        return this.subject.asObservable();
    }
}

Example 2: behaviorsubject in angular 10

@Injectable()
export class TodoService {
  private _todos = new BehaviorSubject<Todo[]>([]);
  private baseUrl = 'https://56e05c3213da80110013eba3.mockapi.io/api';
  private dataStore: { todos: Todo[] } = { todos: [] };
  readonly todos = this._todos.asObservable();

  constructor(private http: HttpClient) {}

  get todos() {
    return this._todos.asObservable();
  }

  loadAll() {
    this.http.get(`${this.baseUrl}/todos`).subscribe(
      data => {
        this.dataStore.todos = data;
        this._todos.next(Object.assign({}, this.dataStore).todos);
      },
      error => console.log('Could not load todos.')
    );
  }
}