0

So, I probably don't understand Observables well. I have snippet like this, and would like to access todos stored in this service via function (from another component) defined in service. Unfortunately, I have no idea how to do this.

todos;
// fetching todos from api
fetchTodos() :Observable<Todo[]>{
    return this.http.get<Todo[]>(api_url);
}

 constructor(private http:HttpClient) {
    this.fetchTodos()
    .subscribe(data => this.todos = data)

}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
coffeble
  • 13
  • 3

1 Answers1

0

To do it right solve your problem as follows.

SERVICE

import { BehaviorSubject, Observable } from 'rxjs';

/* make the plain object a subject you can subscribe to */
todos: BehaviorSubject<Todo[]> = new BehaviorSubject<Todo[]>([]);

constructor(private http:HttpClient) {
    /* get the data and put it in the subject */
    /* every subscriber to this event will be updated */
    this.fetchTodos().subscribe(data => this.todos.next(data));
}

getTodos(): Observable<Todo[]> {
    return this.todos.asObservable();
}

// fetching todos from api
private fetchTodos(): Observable<Todo[]> {
    return this.http.get<Todo[]>(api_url);
}

COMPONENT

constructor(private service: Service) {}

ngOnInit(): void {

    /* here you go. this subscription gives you the current content of todos[] */
    /* whenever it gets updated */
    this.service.getTodos().subscribe(data => {
        console.log(data);
    });
}

PLEASE NOTE

Subscriptions to an Observable should always be finished when you leave a component. The best way to reach this goal in your case is:

modified COMPONENT

import { Subscription } from 'rxjs';

private subscription: Subscription = new Subscription();

constructor(private service: Service) {}

ngOnInit(): void {

    /* add each subscriber to the subscription  */
    this.subscription.add( 
        this.service.getTodos().subscribe(data => {
            console.log(data);
        });
    );
}

ngOnDestroy(): void {
    /* unsubscribe all subscribers at once */
    this.subscription.unsubscribe();
}