Initially, the getCart method is invoked in b-navbar.component.ts
:
export class BNavbarComponent implements OnInit{
appUser: any;
cart$ : Observable<ShoppingCart | null>;
constructor(private auth : AuthService, private shoppingCartService : ShoppingCartService) {}
async ngOnInit() {
this.auth.appUser$.then(dataObservable => {
dataObservable?.subscribe(data => {
this.appUser = data
});
});
this.getCart()
}
async getCart() {
this.cart$ = await this.shoppingCartService.getCart()
this.cart$.subscribe(data => {
console.log("Nav Observable data: ", data);
})
}
The function then retrieves a promise of an observable from shopping-cart.service.ts
:
export class ShoppingCartService {
constructor(private db : AngularFireDatabase) { }
private create(){
return this.db.list("/shopping-carts").push({
// dateCreated : new Date().getTime()
date: "date"
});
}
async getCart(): Promise<Observable<ShoppingCart>>{
let cartId = await this.getOrCreateCartId();
let cart = this.db.object("/shopping-carts/" + cartId);
return new Promise((resolve) => {
cart.valueChanges().subscribe(x => {
let newX = x as ShoppingCart
let items = newX.items
resolve(of(new ShoppingCart(items)))
})
})
}
private async getOrCreateCartId() : Promise<string> {
let cartId = localStorage.getItem("cartId");
if (cartId) return cartId;
let result = await this.create();
localStorage.setItem("cartId", result.key as string);
return result.key as string;
}
}
However, a problem arises when attempting to bind the values in the HTML because the observable returned by the getCart promise resolves a "static" observable. This static observable terminates once resolved, hence the data remains unchanged. Assistance needed! :))
<a class="navbar-item" routerLink="/shopping-cart">
Shopping Cart
<span *ngIf = "cart$ | async as cart" class="tag is-warning is-rounded" >
{{ cart.totalItemsCount }}
</span>
</a>