如何返回角度6中可观察到的对象数组

时间:2018-11-25 14:30:36

标签: angular typescript rxjs observable angular7

我正在用角度7练习todoApp 我在其中存储待办事项到本地存储和CRUD功能。 首先,我将其作为数组存储在本地存储中,但它不适用于所有组件,因此我现在正尝试以可观察的方式返回,但我不知道该怎么做,任何帮助以可观察的方式返回它都将受到赞赏。 >

storage.service.ts

import { Injectable } from '@angular/core';
import { Todo } from './todo';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class StorageService {

  private todos = new BehaviorSubject(Todo);

  constructor() { }

  public setTodos(todos: Todo[]): void {
    localStorage.setItem('todos', JSON.stringify({ todos: todos }))
  }

  public getTodos(){
    let localStorageItem = JSON.parse(localStorage.getItem('todos'));
    if(localStorageItem == null){
        return [];
    }else{
        return localStorageItem.todos;
    }
  }
}

我尝试过

private todos = new BehaviorSubject(Todo);
public setTodos(todos: Todo[]): void {
    localStorage.setItem('todos', JSON.stringify({ todos: this.todos }))
}

但是它给出了错误。 预先感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

这来晚了,但希望能对别人有所帮助。 您可以使用Observable

中的of()以以下格式返回rxjs

按顺序发出可变数量的值,然后发出完整的通知

of()接受任何类型的数据-any | []

签名:of(...values, scheduler: Scheduler): Observable

doc-https://www.learnrxjs.io/learn-rxjs/operators/creation/of

示例-

public getContract(contractId: number): Observable<Contract> {
    const url = `${this._baseUrl}/contracts`;
    // TODO remove on api implementation
    return of(JSON.parse(Data.DUMMY_CONTRACT));
/*
 * below code in uncommented when api is implemented
    return this.http.get<Contract>(url).pipe(
      catchError(this.handleError<any>('Get Contract:'))
    );
*/
  }