Is it possible for my commitment to consistently provide identical values, even when the data varies each time it is invoked?

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>

Answer №1

When your commitment is fulfilled, there is no further "emission" of anything. This marks a significant contrast between promises and observables. Observables have the capability to emit additional values even after their initial emission.

Therefore, it is advisable for your getCart function to simply return the observable stream:

import { map } from 'rxjs';

// continue with 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 will ensure that your promise resolves to the observable stream rather than a solitary value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Browsing HTML Documents with the Click of a Button

After collecting JSON data from a SharePoint list, I am currently in the process of creating an HTML Document. At this point, I have completed approximately 80% of the expected outcome. Due to Cross-Origin Resource Sharing (CORS) restrictions, I have hard ...

`How can I activate caching for getServerSideProps in Next.js?`

We have implemented server-side rendering for a few pages and components. In an attempt to optimize performance, we have been experimenting with caching API responses. export async function getServerSideProps(context) { const res = await getRequest(API ...

learn how to implement local storage for a to-do list application using JavaScript

How do I implement the storage property in this code snippet? The current code is not functioning correctly and resets after each page refresh. Please review my code at the following link: https://jsfiddle.net/74qxgonh/ let values = []; // Accessing Form ...

Tips for launching an angular 2/4 application on web hosting

After successfully creating a local copy of my Angular 4 project, everything is running smoothly on my computer. Now, I am looking to deploy the Angular application onto my shared web hosting in order to make it accessible globally. What steps should I t ...

Send automatically generated information as a component of a submission

Currently, I am struggling to submit dynamically generated content from a table within my form. The form is being generated using Angular 6, but I am having difficulty representing the dynamic content in the FormGroup declaration. import { Component } fr ...

jquery ajax function that returns an object when successful

Below is a brief example of an AJAX call wrapped in a function. MyNS.GetStrings = function (successCallback, errorCallback) { var url = serverUrl + "/GetStrings"; $.ajax({ type: "GET", contentType: "application/json; charset=utf-8", dataType: ...

What is the solution for combining multiple String Literal union types?

I'm dealing with two distinct types of string literals: type X = { type: "A1", value: number } | { type: "A2", value: string }; type Y = { type: "A1", test: (value: number) => void; } | { type: "A2", test: (valu ...

Is using parameterized routes in Node.js a recommended practice or a mistake?

Here is the code snippet I'm working on: router.delete('/delete-:object', function(req, res) { var query; var id = req.body.id; switch (req.params.object) { case 'news' : query = queries['news_del ...

Steps for adding an array of JSON objects into a single JSON object

I have a JSON array that looks like this: var finalResponse2 = [ {Transaction Amount: {type: "number"}}, {UTR number: {type: "string"}} ] My goal is to convert it into the following format: responses : [ { Transaction Amount: {type: "number"}, UTR numbe ...

Choose the span element that is contained within multiple div elements

Is there a way to target a specific span tag and change the text color to white without using IDs? I am trying to modify the CSS of the friend section on a page but cannot add any IDs. This is for the friend section on the website younow. <div id="left ...

Discovering Constraints on File Size: API Response Encoded in Base64 Visible Within 1 Megabyte, Overcoming Rendering Obstacles

Currently, I am encountering a hurdle in my Next.js application when trying to upload images larger than 1 MB. While the app works seamlessly with smaller images, it faces challenges when dealing with larger ones. Initially, there was a browser console er ...

Verifying Content in JavaScript

Here is a snippet of code I used to validate a Registration form on a content page. However, the validation part seems to not be functioning properly. Any assistance would be greatly appreciated. Master Page <%@ Master Language="C#" AutoEventWireup="t ...

Identifying a Malformed URI in JavaScript

In JavaScript, it is considered a best practice to use certain patterns to detect errors instead of solely relying on try-catch blocks. One easy way to do this is by using TypeError: if (typeof foo !== "number") { console.log("That ain't a number!" ...

Executing numerous tests on a single response using Node.js along with Chai, Mocha, and Should

I have a setup similar to the one below that allows me to perform a series of API tests using Mocha. While this method works well, it involves making an individual API call for each test. My goal is to streamline the process by utilizing the same API cal ...

Combining Auth Observables in Angular: A Complete Guide

Currently, I'm working on an Angular service that leverages AngularFire's auth observable to monitor user state changes. Upon a user signing in, the application should retrieve a user document from MongoDB. To enable components to consume this da ...

Is it possible for a lambda in TypeScript to have access to the class scope but return undefined

In my TypeScript code, I have a class used as a Pipe in Angular 2 to render markdown. It compiles successfully but encounters a runtime exception on a specific line: var Remarkable = require('remarkable'); @Pipe({ name: 'markdown' ...

Error: The function setOpenModal is not defined

I'm currently working on creating a login modal popup that will appear when a button inside a navbar is clicked. However, I'm encountering the following error: TypeError: setOpenModal is not a function Despite going through various discussions ...

Encountered difficulties in deploying functions on Firebase Cloud Functions

While developing the Firebase Cloud Functions, I organized the files based on each function. Unfortunately, numerous errors occurred during deployment. Error [debug] [2022-07-19T14:36:17.677Z] <<< [apiv2][body] GET https://us.gcr.io/v2/xxxxxx/gcf ...

Discover the steps for integrating an object into a Ext.grid.Panel using Sencha Ext Js

Currently, I am utilizing Sencha Ext Js 4 and have integrated an Ext.grid.Panel into my project. I am interested in adding another element inside the header, such as a textbox. Is this achievable? {filterable: true, header: 'Unique' /*Here i w ...

Conflict arises between Angular $scope and the file input type

I have been attempting to convert a file into a byte array using AngularJS. The conversion process is successful and I am able to add the byte code and filename to an array ($scope.FileAttachments). However, there seems to be an issue with ng-repeat not wo ...