I have the following Angular 7 service on an application:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';

import { Observable } from 'rxjs';

import { Todo } from './todo';

@Injectable({
  providedIn: 'root'
})

export class TodoService {

  constructor(private httpClient: HttpClient) { }

  public get(): Observable<Todo> {
    return this.httpClient.get<Todo>(`todos`);
  }

  public create(todo) {
    const headers = new HttpHeaders({ 'Content-Type': 'application/json' });

    return this.httpClient.post(`todos`, { headers: headers });

  }

}

I would like to simulate this service with a list of Todos defined in code.

How can I do this?

1 Answers

1
Tim Klein On Best Solutions

You can use the RxJs BehaviorSubject to simulate an Observable of data from some external source.

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

import { Observable, BehaviorSubject } from 'rxjs';

import { Todo } from './todo';

@Injectable({
  providedIn: 'root'
})

export class TodoService {

  todos: BehaviorSubject<Todo[]> = new BehaviorSubject([]);

  public get(): Observable<Todo[]> {
    return this.todos.asObservable();
  }

  public create(todo: Todo) {
    this.todos.next(this.todos.value.concat(todo));
  }

}