Retrieve information and transform it into a dynamic variable using Firebase

I am trying to retrieve data from the current user, specifically their company named "ZeroMax", and then store this data in a global variable. The purpose of this variable is to define the path for Firebase. I believe my code gives a clear understanding of my question. Everything seems to be functioning correctly, except for the assignment

this.comp = user['company'];

Shown below is my drivers.service.ts file:

export class DriversService {

  user: User;
  comp = '';
  constructor(private db: AngularFirestore, private auth: AuthService, private afAuth: AngularFireAuth) { }

 getUsers() {
  return this.auth.user.pipe(
    take(1),
    map(user => {
      //  user['company'];
      this.comp = user['company'];
      return user['company'];
    })
  )
 }

  findUser(value) {

    if (this.comp.length <= 0) {
      return this.getUsers().pipe(map(user => {
      this.comp = user;
      console.log('Bye', this.comp);
      return this.comp;
      }));
    }

    let email = this.db.collection(`companies/${this.comp}/users`, ref => ref.where('email', '==', value)).valueChanges({ idField: 'id' }).pipe(
      take(1)
    );
    let name = this.db.collection(`companies/${this.comp}/users`, ref => ref.where('name', '==', value)).valueChanges({ idField: 'id' }).pipe(
      take(1)
    );
    return [email, name];
  }
}

Moreover, this is the content of my add-driver.page.ts file:

export class AddDriverPage implements OnInit {
 
  users = [];
  participant = '';
  form: FormGroup;

  constructor(private driverService: DriversService, private loadingCtrl: LoadingController, private auth: AuthService) { }

  ngOnInit() {
    
  }

  addDriver() {
    const obs = this.driverService.findUser(this.participant);

    forkJoin(obs).subscribe(res => {
      if (!res || !res.length) {
        return console.log('Received undefined');
      }
      for (let data of res) {
        if (data.length > 0) {
          this.users.push(data[0]);
          //console.log(res);
        }
        console.log(res);
      }
      console.log('Operation successful:', this.participant)
      this.participant = '';
    }, error => {
   console.log('An error occurred here: ', error);
});
  }
}

Answer №1

It doesn't matter where you try to use the this.comp variable, it's all about the timing of when you access it. When your code

this.db.collection(`companies/${this.comp}/users`)
is executed, the assignment this.comp = user may not have happened yet.

Any piece of code that relies on data from a database should be placed inside the callback function that gets called once the data is ready.

For instance:

if (this.comp.length <= 0) {
  return this.getUsers().pipe(map(user => {
    let email = this.db.collection(`companies/${user}/users`, ref => ref.where('email', '==', value)).valueChanges({ idField: 'id' }).pipe(
      take(1)
    );
    let name = this.db.collection(`companies/${user}/users`, ref => ref.where('name', '==', value)).valueChanges({ idField: 'id' }).pipe(
      take(1)
    );
    return [email, name];
  }));
}

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

Show information retrieved from one API request within another API request

Currently, I am in the process of retrieving data from the Youtube API by utilizing 2 separate requests. One request is used to fetch a list of videos, while the other request provides details for each individual video. The initial request successfully di ...

Navigating through Expo with Router v3 tabs, incorporating stack navigation, search functionality, and showcasing prominent titles

I've been working on designing a navigation header similar to the Apple Contacts app, with a large title and search function, but only for the Home Screen. All other tabs should have their own unique settings, like different titles or hidden navigatio ...

Issues with tsconfig Path Aliases in Angular 8+ when used in .spec files

While working on Angular testing, I encountered an issue where my spec files were not recognizing paths and displaying a red squiggle import warning in VS Code (and appearing under Problems), even though they functioned properly otherwise (testing worked, ...

Removing a key from an index signature in Typescript - a step-by-step guide

In my web application built with Angular, we encountered a need for a data type to store translations of strings in different languages. To address this requirement, a team member defined the following type: export class TranslatedString { [language: str ...

Is Operator Overloading supported in Typescript?

I'm curious about whether operator overloading is supported in typescript. If it does exist, I'd be happy to provide an example or a link for you to explore further. ...

Can multiple Observables be used to display FormArray data within a FormGroup effectively?

I've spent countless days attempting to asynchronously display dynamically loaded FormArray data without success. Essentially, I have a FormGroup that is created on click and shown in a modal window (no issues with displaying data loaded in the subscr ...

Determine the class of an object within the "keyof" parameter by utilizing both property and generic types

I have a requirement to create an interface with generic types that can accept an object with keys representing "root field names" and values as arrays of objects defining sub-fields with the key as the name of the sub-field and the type as the value' ...

What is the best way to retrieve the elements within a third-party selector?

Within the same package, I am working with a selector called "own date picker." This selector includes a "div" element that contains an "input" field. I need to modify the CSS of this input field, but cannot directly access it in my project because it is p ...

How come a null variable continues to widen to type any even when strictNullChecks is enabled?

According to the TypeScript Documentation, if strictNullChecks is true, there should be no type widening. Also, the typeof nul should be null. let nul = null; // typeof nul = any let undef = undefined; // typeof undef = any Check it out in the Playground ...

Creating a dynamic configuration for service instantiation in Angular 4/5

Currently working on a library that has an AuthModule with an AuthService for managing OAuth2 authentication using oidc-client-js. I want the application using this library to be able to set up the configuration for the OAuth client. One way to do this is ...

typescript locate within the union type in the mapping expression

Consider the following: type X = { label: 'Xlabel', X_id: 12 }; type Y = { label: 'Ylabel', Y_id: 24 }; type Z = { label: 'Zlabel', Z_id: 36 }; type CharSet = X | Y | Z; I am looking for type CharSetByLabel = Map<CharSet& ...

Converting JSON to TypeScript with Angular Casting

I'm facing an issue detailed below. API: "Data": [ { "Id": 90110, "Name": "John", "Surname": "Doe", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="472d282f2923282207202a262e2b ...

Issue occurs when using Angular Firebase $createUser method

I'm stuck on this issue. I'm attempting to set up a user with AngularFire using $firebaseAuth instead of the deprecated FirebaseSimpleLogin, as advised in the documentation. I am confident that the form is submitting a valid email and password, b ...

The CoreUI Sidebar gracefully hovers over the main page content

I recently started using CoreUI to design the layout for my application, but I ran into an issue while trying to integrate the Sidebar. Although the Sidebar is visible on the left side, I'm having trouble making sure that the router-view takes up the ...

How to show ngFor value from Angular in a separate tag

I have a list of companies that I want to display in the following format: <div class="col-md-4"> <select ngModel="selectedCompany" style="width:400px;"> <option *ngFor="let x of mycompanylist&q ...

I'm having trouble retrieving the information as it is showing as undefined. Can anyone offer any advice?

Attempting to extract specific information from an API response has proven challenging. Despite my efforts to isolate the desired data, all listed details appear as undefined. import { HttpClient } from '@angular/common/http'; import { Injectable ...

Is it possible to utilize Angular translate to support multiple languages for individual components or modules?

Utilizing ngx-translate to switch the language of my application has proven to be quite challenging. My application consists of different languages specifically for testing purposes and is divided into separate modules with lazy loading functionality. As ...

Setting up email verification for Firebase in Vue.js: A step-by-step guide

I'm in the process of creating a Vue.js/Firebase authentication interface inspired by an example I stumbled upon on Github. The code utilizes the .sendEmailVerification() function to send a verification email when a user signs up for an account. While ...

Troubleshooting TypeScript compatibility with SystemJS when encountering problems with the .js extension

Initializing my TypeScript file with the import statement below. It's important to note that the lack of a .ts extension indicates that I am importing a TypeScript module: import githubService from './github.service'; Through transpilation ...

The element of type 'OverridableComponent<LinkTypeMap<{}, "a">>' cannot be assigned to a 'ReactNode'

I'm currently working on a project where there's a component named ListItemTextStyle. Within that component, the prop type is defined as follows: import { LinkProps, ListItemButtonProps, } from '@mui/material'; type IProps = LinkP ...