My Angular2 service is designed to serve as a shared resource across different components. The components interact with the public books
and selectedBook properties
. I aim to store the list of books and the currently selected book in the service, only populating them on the initial 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];
}
}
I encounter problems when trying to access the array or invoke setSelecteBook(id)
before it is populated, leading to crashes. I have explored using Observables for guidance, but haven't come across a similar enough scenario to adapt for solving my issue.