将数组作为行为主体可观察到

时间:2018-11-29 06:23:42

标签: angular typescript rxjs observable angular6

我将在角度6中应用todo过滤器,并基于是否完成dodo(仅完成(选中)todo)在单击完成链接时显示todo。 我设法获得在todoService(getTodos)函数中完成的待办事项。 但是由于getTodos是Observable,因此不允许我返回todos数组

这是我的服务代码

  public getTodos(query = ''): Observable<Todo[]>{
    if(query === 'completed' || query === 'active'){
      const isCompleted = query === 'completed';
      let todos = this.allTodos.filter(todo => todo.completed === isCompleted);
      console.log(todos);
      // this.storageService.getTodos().subscribe(todos => this.allTodos.filter(todo => todo.completed === isCompleted));
      // return this.todos.next('todos');
      return this.todos.asObservable();
    }else{
      return this.todos.asObservable();
    }
  }

stackblitz中项目的完整链接

Project link

PS:我是新手,现在仍在学习Observables / rxjs

2 个答案:

答案 0 :(得分:0)

您的服务中已经有BehaviorSubject。您只需在服务中添加公共Observable

public todos$: Observable<Todo[]> = this.todos.asObservable();

然后在您的getTodos方法中:

public getTodos(query = ''): Observable < Todo[] > {
  if (query === 'completed' || query === 'active') {
    ...
    this.todos.next(todos);
  }
  else {
    ...
  }
}

在您的组件中,您可以使用以下命令将todos的{​​{1}}移至此subscribe

Observable

答案 1 :(得分:0)

    Todo[] myTodos;

    todoService.getTodos('').subscribe(response => {
        //here you can response - what you return from service
        this.myTodos=response;
    });

响应就是您从服务中返回的东西