Retrieving the returned value from an Observable of any type in Angular Typescript (Firebase)

I am working on retrieving data from my Firebase User List using the following code:

currentUserRef: AngularFireList<any>
currentUser: Observable<any>;

var user = firebase.auth().currentUser;

this.currentUserRef = this.af.list('usuarios', ref =>
ref.orderByChild('email').equalTo(user.email));
this.currentUser = this.currentUserRef.valueChanges();
this.currentUser.subscribe(res => console.log(res[0].condominio));

The retrieved data contains two properties: 'condominio' and 'email'.

After displaying the data in the console with `console.log(res[0].condominio)`, I need to store it in a variable like this:

userCond: string;

However, when I try to assign the 'condominio' property from 'res' to 'userCond', it doesn't seem to work:

this.currentUser.subscribe((res) => { this.userCond = res[0].condominio });

What could be going wrong here?

"angularfire2": "^5.0.0-rc.11",
"firebase": "^5.3.1",
"ionic-angular": "3.9.2",

EDIT:

    export class HomePage {

    currentUserRef: AngularFireList<any>
    currentUser: Observable<any>;

    moradorRef: AngularFireList<any>
    morador: Observable<any>;

   userCond: string;

   constructor(
    public authService: AuthService,
    public userService: UserService,
    public navCtrl: NavController,
    public navParams: NavParams,
    public af: AngularFireDatabase
   ) {

   }

   ionViewCanEnter(): Promise<boolean> {
     return this.authService.authenticated;
   }

   ionViewDidLoad(){
    debugger;
    //TRAZ AS MESMAS INFORMAÇÕES
    //this.userService.getCurrentUser();
    var user = firebase.auth().currentUser;

    //const _this = this;

    this.currentUserRef = this.af.list('usuarios', ref =>
    ref.orderByChild('email').equalTo(user.email));
    this.currentUser = this.currentUserRef.valueChanges();
    //this.currentUser.subscribe(res => 
    console.log(res[0].condominio));
    this.currentUser.subscribe(res => {
      debugger;
      this.userCond = res[0].condominio;
    });

    console.log(this.userCond);

Answer №1

  When subscribing to currentUser, assign the class instance to a new variable to avoid confusion:
  
    this.currentUser.subscribe(res => {
      const _this = this;
      _this.userCond = res[0].condominio;
    });

By using this approach, you can ensure that 'this' refers to the correct context when accessing properties within the subscription.

Answer №2

Declare the userCond variable as an Observable.

userCond: Observable<string>;

Afterwards, assign the value of the condominio property to userCond while retrieving data from the firestore.

this.currentUserRef = this.af.list('usuarios', ref =>
                              ref.orderByChild('email').equalTo(user.email));
this.userCond = this.currentUserRef.valueChanges()
                                       .pipe(map(res => res[0].condominio));

Subsequently, you can subscribe to userCond in order to access its value whenever needed.

Answer №3

One obstacle is ensuring that the Subscription completes before accessing the class variable userCond. Since Subscriptions are not synchronous, it's important to call the method you wish to use from within the Subscription.

this.currentUser.subscribe(res => {
  this.userCond = res[0].condominio;
  this.performActionAfterSubscription();
});

performActionAfterSubscription() {
   // Access the this.userCond variable here
}

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

Having trouble locating the Angular Material core theme within the asp.net core 2.0 template using Angular 5

CustomConfig.js const treeModules = [ '@angular/animations', '@angular/common', '@angular/compiler', '@angular/core', '@angular/forms', '@angular/http', '@angular ...

Implementing type inference for response.locals in Express with TypeScript

I need to define types for my response.locals in order to add data to the request-response cycle. This is what I attempted: // ./types/express/index.d.ts declare global { declare namespace Express { interface Response { locals: { ...

Customize your Loopback 4 OpenAPI with NSWAG by making filters optional and specifying data types

I am encountering an issue with the Loopback 4 filter on the generated endpoints being marked as required in my Nswag typescript file. I need it to be optional, but I am struggling to locate where this requirement is originating from. The endpoint from my ...

Is there an alternative method to invoke the function aside from setTimeOut()?

if(i==1){ this.resetScreens(); this.editJobScreen1 = true; if(this.selectedLocations.length > 0){ this.locationService.getLocationByInput({ maxResultCount:16, skipCount: 0 }).subscribe((ele)=>{ ...

The installation of an NPM package globally was blocked due to EACCES permission error

I tried installing firebase tools for firebase hosting by following the documentation and running the command sudo npm install -g firebase-tools. However, I encountered the following warnings and errors in my terminal: npm WARN deprecated <a href="/cd ...

Type of Angular Service Issue: string or null

I'm encountering a persistent issue with my Angular code, specifically while calling services in my application built on Angular 13. The problem arises when trying to access the user API from the backend, leading to recurrent errors. Despite extensive ...

How can I create a universal "Add" button in Angular that can be used across all child components?

Currently, I am working on a straightforward application featuring a toolbar at the top of the screen. Within this toolbar, there is a + button designated for adding content. The functionality of this + button changes based on which component is currently ...

Ways to make a component gradually appear and disappear in an Angular application

I have developed a task management application using Angular and I wanted to implement a fading effect for each task when it is created and before it is deleted. Despite successfully applying the fade in effect at the todo-item component level, I encounter ...

The object is not a valid function

Within this class object, I have an instance of a class that I am unable to call its functions within. Despite the IDE allowing me to call the getPoistionDiagram function: export class NodeW { childrenIds: string[]; diagram?: { coordinates: { ...

Accessing JSON data stored locally and initializing it into a TypeScript variable within a React application

I'm new to working with JSON arrays and I'm facing a challenge. I am looking for a way to load data from a JSON file into a Typescript variable so that I can perform a specific operation that involves arrays. However, I'm unsure of how to ac ...

Angular definitely typed does not convert into JavaScript

After installing TypeScript on my VS2013, I obtained the Angular 1.5 Definitely Typed from the NuGet package manager. Although angular.d.ts and its components do not generate angular.js file, when I create another TypeScript file like file1.ts, the file1. ...

ngOnChanges fails to trigger

I have set up a StackBlitz example (without server side code) which demonstrates an issue with reassigning a variable asynchronously from the backend. I need to update these values so that all objects in the array are of the same type for use in a select ...

Finding parameters in Angular 4

I am working on implementing a multilanguage feature in an Angular app and I need to establish the default language when the site loads. The two languages supported are Spanish and English, with Spanish being the default language. In order to achieve this, ...

Using methods from one component in another with NgModules

There are two modules in my project, a root module and a shared module. Below is the code for the shared module: import { NgModule } from '@angular/core'; import { SomeComponent } from "./somecomponent"; @NgModule({ declarations: [SomeCompon ...

Unexpected behavior: Angular post request does not include the expected request body

Embarking on my initial solo Angular project... I am endeavoring to make a post request to my freshly created web service and have implemented the following code: headers = new HttpHeaders( {'Content-Type':'text/plain'} ); l ...

Exploring Angular 2: How to loop through reactive form controls and set them as dirty

Is there a way to trigger the markAsDirty function for all the elements within a specific FormGroup in Angular? ...

How can one access Firestore Timestamp in its raw format?

We are facing an issue with serializing JSON data when working with Firestore as our database. While it is recommended to use the TimeStamp object for writing dates to Firestore, we have encountered a challenge. I have a converter that handles converting ...

Angular 4: Triggering a function by clicking a link with specific parameters

I am relatively new to working with Angular 4. I have an anchor tag that, when clicked, should redirect me to a link where I also need to pass parameters. I'm unsure if my current approach is correct or not. Above all, I really need guidance on how to ...

Alert: Zone.js has identified that the ZoneAwarePromise '(window|global).Promise' has been replaced with polyfills. Kindly address this issue

Recently, I updated my Angular application from version 8 to 9. After updating the packages and successfully compiling the application, I encountered an error message in the Chrome browser console: Error: Zone.js has detected that ZoneAwarePromise `(wind ...

The data type 'T[K]' does not meet the required conditions of 'string | number | symbol'

I am currently in the process of developing a straightforward function to eliminate duplicates from an array using TypeScript. While I acknowledge that there are numerous methods to accomplish this task, my main objective is to enhance my understanding of ...