behaviorsubject angular 8 code example
Example: behaviorsubject in angular 10
@Injectable()
export class TodoService {
private _todos = new BehaviorSubject<Todo[]>([]);
private baseUrl = 'https://56e05c3213da80110013eba3.mockapi.io/api';
private dataStore: { todos: Todo[] } = { todos: [] };
readonly todos = this._todos.asObservable();
constructor(private http: HttpClient) {}
get todos() {
return this._todos.asObservable();
}
loadAll() {
this.http.get(`${this.baseUrl}/todos`).subscribe(
data => {
this.dataStore.todos = data;
this._todos.next(Object.assign({}, this.dataStore).todos);
},
error => console.log('Could not load todos.')
);
}
}