Understanding Observable.count and how to avoid unexpected results
To accurately determine the length of an array from Observable results, consider implementing the following approach:
BookStoreService.ts
...
getBookStore() : Observable<Bookstore> {
this.bookstore$ = this.http.get(...)
.map( (response:Response) => response.json() )
.map( response => response.bookstore); // Check if the JSON payload you require is wrapped in another container
return this.bookstore$;
}
Component.ts
...
bookstore$ : Observable<Bookstore>;
bookstores: Bookstore[];
numberOfBookStores:number;
constructor(private bookService:BookService) {}
..
this.bookService.getJobs()
.subscribe(
bookstores => {this.bookstores = bookstores;
this.numberOfBookstores = this.bookstores.length;
},
err => { this.bookstores = [] as BookStore[];
// Handle errors such as 404 more extensively in final code for better user feedback
},
() => {
}
);
Update:
If your goal is only to iterate through the list in your HTML template, declaring the bookstores array property may not be necessary. This was demonstrated to show how to calculate the size of the returned collection of bookstores.
You can utilize syntax like this:
<tr *ngFor="let bookstore of (bookstore$ |async) as bookstores;
trackBy bookstore?.id; let i = index">
<td>{{bookstore.numberofBooks}}
<tr/>
Learn more about:
- *ngFor trackBy, even, odd, first, last attributes here.
- Using Async pipe for handling entire block of HTML template with AS here
Additionally, explore libraries like Lodash and Underscore for computing the total count of books. Although I have not personally used Underscore.
Check out this basic example to begin.
If you are feeling adventurous, delve into this Functional Programming in Javascript Tutorial