简体   繁体   中英

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. I managed to get todos that are completed in todoService (getTodos) function. But as getTodos is Observable it was not allowing me to return me to todos array

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

Project link

PS: I am new to angular and still learning Observables/rxjs

You already have a BehaviorSubject in your Service. You can just add a public Observable to your service:

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

And then in your getTodos method:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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