Niang Moore
Niang Moore

Reputation: 506

Angular - Display Item by Category

I would like to display the books under its category but as LoadBooksByCat(catId) is called for each category Id, it will updates all the previous books that was displayed to the new list

categories: Observable<any[]>;
 myBooks: Observable<any[]>;
 
 this.db.GetDatabaseState().subscribe(rdy => {
  if (rdy) {
    this.categories = this.db.getCategories();
    }
}

LoadMyBooksByCat(catId){
    this.myBooks = this.db.LoadBooksByCat(catId);
  }



  
  <div *ngFor="let cat of categories | async">
          <ion-label>
            {{ cat.CategoryName }}
          </ion-label>
          
        {{LoadMyBooksByCat(cat.id)}}

        <ion-row>
        <ion-col *ngFor="let books of myBooks | async">
          <ion-item>
              <ion-label>{{books.bookName}}</ion-label>
          </ion-item>
        </ion-col>
       </ion-row>

</div>
  

this is getCategories and LoadBooksByCat method which I called from the service

getCategories(): Observable<Category[]> {
  return this.categories.asObservable();
}

LoadBooksByCat(catId:number){
  let mybooks: mybooks[] = [];
   this.database.executeSql('SELECT mybooks.bookName, mybooks.id, mybooks.catId, Category.CategoryName AS mybooks FROM Books JOIN Category ON Category.id = mybooks.catId WHERE mybooks.catId=' + catId, []).then(data => {
    
    if (data.rows.length > 0) {
      for (var i = 0; i < data.rows.length; i++) {   
        mybooks.push({ 
          id: data.rows.item(i).id,
          catId: data.rows.item(i).catId,
          bookName: data.rows.item(i).bookName
         });
      }
    }
    this.mybooks.next(mybooks);
  });
  return this.mybooks.asObservable();
}

Here is what Categories and Books db looks like

Categories

id CategoryName

1, 'Finance'

2, 'Communication'

Books

id catId bookName

1, 1, 'Finance 101'

2, 1, 'Basic Economy'

3, 2, 'Crucial Conversation'

4, 2, 'Influence'

Upvotes: 1

Views: 688

Answers (1)

minigeek
minigeek

Reputation: 3166

There is lot of asynchronous operations happening in your code. Make it sequential. Instead of using string interpolation, make changes in .ts file

Call getbookbycat inside subscribe of getCategory so it will more synchronous and create a map to render on HTML. This will print your key value pair of each category and its book.

Upvotes: 1

Related Questions