Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

111
Vistas
My promise returns the same value every time it's called despite having different data?

So first the getCart function is called 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);
    })
  }

Which looks in shopping-cart.service.ts and gets a promise of an observable:

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;
  }
}

Now the issue arises when interpolate the values in my html, since the observable returned in the getCart promise resolves a "static" observable, meaning it terminates the observable when resolved, thus the data is never updated. Please help :))

<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>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Once your promise gets resolved, it doesn't "emit" anything after that. This is one key difference between promises and obsevables. Observables can emit more values even after they emit the first.

So, you should make your getCart return just the observable stream:

import { map } from 'rxjs';

// rest of your code

async getCart(): Promise<Observable<ShoppingCart>>{
  let cartId = await this.getOrCreateCartId();
  let cart = this.db.object("/shopping-carts/" + cartId);
  return cart.valueChanges()
    .pipe(map(x => {
      let newX = x as ShoppingCart
      let items = newX.items
      return new ShoppingCart(items)
    }))
}

This way, your promise resolves to the observable stream instead of a single value.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda