在Angular中模拟Todos服务

时间:2019-05-13 14:41:45

标签: angular angular7

我在应用程序上具有以下Angular 7服务:

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

  }

}

我想用代码中定义的Todo列表来模拟此服务。

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用RxJs BehaviorSubject模拟来自某些外部源的数据的Observable。

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

}