I have an Angular2 service as follows. I am trying to use this as a shared service between multiple components. If it matters, the components are binding directly to the public books
, and selectedBook properties
I want to cache the list of books and the currently selected book on the service and only call populate these on the first call.
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
@Injectable()
export class BookService {
public books: Book[];
public selectedBook: Book;
constructor(private http: Http,
private router: Router) {
this.http.get('/api/book/list')
.subscribe(result => this.books = result.json() as Book[]);
}
public getBooks() {
return this.books;
}
public setSelectedBook(id) {
this.selectedBook = this.books.filter(x => x.id == id)[0];
}
}
The problem is that sometimes I'm trying to read the array or call setSelecteBook(id)
before the array is actually populated, which causes a crash. I have been trying to find an example of how to use Observables, but I can't find a scenario close enough to mine to be able to figure out how to adapt it to solve my problem.