Angular - delay execution until the variable has a value

When the ngOnInit() function is called, the first line of code retrieves a value from local storage which is then used to filter data from the database.

Both actions happen simultaneously, resulting in an issue where I don't receive the expected result. How can I make the second function wait for the first one to retrieve the value?

Here is the ts code snippet:

 ngOnInit() {

    //get id of user
    this.storage.get('loggedInUser').then((val) => {
      console.log('Your user ID is', val);
      this.loggedInusr = val;
    });

    firebase.firestore().collection(`todos`)
  .where("assignTo", "==", this.loggedInusr) // doesn't get value here, works if hard coded
  .get()
  .then(querySnapshot => {
      querySnapshot.forEach(function(doc) {
          console.log("assignTo");
          console.log(doc.id, " ===> ", doc.data());
      });
    });

    ...

Answer №1

One suggestion is to place the 2nd procedure within the handling of the 1st procedure. You can try implementing the following code snippet:

ngOnInit() {
  // Retrieve the user's ID
  this.storage.get('loggedInUser').then((val) => {
    console.log('Your user ID is', val);
    this.loggedInusr = val;

    // Query Firestore for todos assigned to the logged in user
    firebase.firestore().collection(`todos`)
      .where("assignTo", "==", this.loggedInusr)
      .get()
      .then(querySnapshot => {
        querySnapshot.forEach(function(doc) {
            console.log("assignTo");
            console.log(doc.id, " ==> ", doc.data());
        });
      });

  });
  .
  .
}

Answer №2

Utilizing rxjs switch map can help achieve this functionality, ensuring automatic updates whenever there are changes in the observable values.

import { from } from 'rxjs';

     from(this.storage.get('loggedInUser'))
      .pipe(switchMap((loggedUser) => 
              from(firebase.firestore().collection(`todos`).where("assignTo", "==",loggedInusr) .get()).subscribe(querySnapshot => {
                querySnapshot.forEach(function(doc) {
                console.log("assignTo");
                console.log(doc.id, " ===> ", doc.data());
            });
    ))

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

Collaborative Animation Techniques for Modern Angular Versions (7 and up)

Can animation triggers be shared across the entire project? I'm hoping to avoid having to include an import and animation meta declaration in every new component. Appreciate any help on this! ...

Timestamps are no longer recognized in Highstock charts once data has been added

In my highstock chart, I am pulling data from a REST api and everything appears correct. However, there is no data available between 19:00 and 05:00. I would like this absence of data to be reflected in the chart without cropping out that time span from th ...

Angular 5 and the benefits of concurrent requests

My goal is to execute multiple requests in parallel, fetch the results, and combine them. To achieve this, I have implemented the following function: getStudent(query): Observable<any> { const code = this.http.get( `http://localhost ...

Angular: Tailoring the Context Menu

Currently, I am utilizing a helpful tutorial to implement a custom context menu feature. The main issue I am facing is that when a user interacts with the list items, I want the correct index of each item to be displayed. However, at the moment, clicking o ...

The negation operator in Typescript is failing to negate as expected

When a user changes a multiselect element, there is a function that runs to control the visibility of an error message: getVisibility(multiselect) { if ((multiselect.selectedCategories.length < 1 && !multiselect.allSelected) && th ...

A guide on the correct way to fork an Ionic Stencil Component

I am interested in customizing the columns and position of ion-datetime to use it in my Ionic app. However, I am unsure how to approach this without resorting to messy copy-and-paste solutions. Are there any better methods for achieving this customizatio ...

Using JavaScript/TypeScript to sort through and separate two arrays

Creating a list of checkboxes on a UI allows users to toggle and filter data results. To achieve this, I am storing the selected checkboxes as a string array. The structure of my code is outlined below: export interface IMyObjectFromAPI { status: { ...

Issue: The requested file or directory '/root/.ionic/daemon.log' does not exist

Recently, I encountered an error on Windows 10. In an attempt to resolve it, I performed a clean installation of Ubuntu over my existing Windows system, wiping everything out. However, even after downloading the latest versions of NodeJS, Ionic, and Cordov ...

Ways to selectively deactivate client-side functionality

I have implemented a server-side rendered app with transitions, including a 404 error page that I placed in a lazy module to avoid increasing the size of loaded JavaScript. While this setup is functioning correctly, there is some flickering when the clien ...

Exploring the art of styling in Angular6

I am looking to change the text color when a specific ID is clicked <nav class="navbar "> <ul class="navbar-nav"> <li *ngFor="let item of items"> <a class="nav-link" >{{item.title}}</a> ...

Utilizing Angular resolver to inject the router functionality

In my Angular (v13) application, I have defined a resolver to interact with a Wordpress backend. The purpose of this resolver is to determine the post type and ID from Wordpress when a user accesses a URL, and then route accordingly (to a post list, single ...

Conceal a division based on its numerical position

I'm having trouble figuring out how to hide multiple divs based on an index that I receive. The code snippet below hides only the first div with the id "medicalCard", but there could be more than one div with this id. document.getElementById("medical ...

"Having trouble subscribing? The first attempt doesn't seem to be working

I'm currently working on some TypeScript code that searches for the nearest point around a user in need of car assistance by checking a database. Once the nearest point is identified, the code retrieves the phone number associated with it and initiate ...

Implement a class attribute to the parent <div> element using React and TypeScript

I'm trying to figure out how to achieve this task. I need to assign a class upon clicking on an element that is not directly in my code, but rather in one of its parent elements. My initial thought was to accomplish this with jQuery using the followi ...

What is the best way to create a TypeScript function that merges actions together?

I am currently working on a TypeScript function similar to the following: import multipleActionObject from page; it("should be able to perform multiple operations", () => { multipleActionObject.chooseIndex(4).setValue(10); } Inste ...

What imports are needed for utilizing Rx.Observable in Angular 6?

My goal is to incorporate the following code snippet: var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: { lat: -25.363, lng: 131.044 } }); var source = Rx.Observable.fromEventPattern( function (han ...

Cross-Origin Resource Sharing problem with identical URL

I encountered a CORS issue with my Angular 6 application running on port 4200 and using an API on port 3000. To address this, I implemented the following code snippet on the server side: app.use(function(req, res, next) { res.header("Access-Control-Allo ...

What is the best way to incorporate styled components and interpolations using emotion theming?

I've been building a React web application with a dynamic theme feature using the emotion-theming library. This allows users to switch between different environments, each with its own unique theme. To achieve this, I created my own CustomThemeProvide ...

The issue of the Angular service being consistently undefined arises when it is invoked within an

I have already researched numerous other SO questions, but none of the solutions worked for me. My goal is to implement an async validator that checks if a entered username already exists. However, every time I type a letter into the input field, I encoun ...

Error encountered on login page: The protocol 'http' does not exist (related to HTML, TypeScript, Angular2, and JavaScript)

Screenshot of the issue: Access the complete project here: Link to a Plunker example of a log-in screen: http://plnkr.co/edit/j69yu9cSIQRL2GJZFCd1?p=preview (The username and password for this example are both set as "test") Snippet with the error in ...