简体   繁体   English

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

[英]Returning array as Observable to Behavior subject

I am applying todo filters in angular 6 with routing based on if todo is completed only completed(checked) todos should display on clicking completed link. 我根据待完成的待办事项在路由中应用角度为6的待办事项过滤器,仅在单击已完成链接时才显示已完成(已选中)待办事项。 I managed to get todos that are completed in todoService (getTodos) function. 我设法获得在todoService(getTodos)函数中完成的待办事项。 But as getTodos is Observable it was not allowing me to return me to todos array 但是由于getTodos是Observable的,因此不允许我返回todos数组

Here is my code for service 这是我的服务代码

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

Full Link of project in stackblitz Stackblitz中项目的完整链接

Project link 项目链接

PS: I am new to angular and still learning Observables/rxjs PS:我是新手,现在仍在学习Observables / rxjs

You already have a BehaviorSubject in your Service. 您的服务中已经有一个BehaviorSubject You can just add a public Observable to your service: 您可以在服务中添加一个公共的Observable

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

And then in your getTodos method: 然后在您的getTodos方法中:

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

And in your Component, you can get the todos by subscribe to this Observable using this: 在您的组件中,您可以使用以下方法subscribeObservable来获取todos

todos;
constructor(private todoService: TodoService, ...) {}
...
this.todoService.todos$.subscribe(todos => this.todos = todos);
    Todo[] myTodos;

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

response is sothmething what you return form service 响应就是您从表单服务返回的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM