Error message: The variable referenced in the subscription is not recognized outside the scope in Angular 2 when

When working with my Angular2 component, I encountered a situation where I needed to store a value from Firebase into a variable inside the constructor. Like so:

this.dbAction.getDB().take(1).subscribe(data => {
  this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder']; 
  console.log(this.userVisitOrder); // Value exists
});

Interestingly, I needed to use this variable in constructing an Observable to access specific Firebase data. However, I faced an issue within my constructor:

this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder)); // Here the value is undefined

It seems like an asynchronous problem, but how can I make sure to access the data stored in my variable?

Describing the getDb() function in my dbAction Service:

getDB() {
  return this.afDatabase.list(`data`).valueChanges().map((data) => data);
}

Attempting to combine the codes by putting the second code snippet within the first:

this.dbAction.getDB().take(1).subscribe(data => {
  this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder'];

  this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder));
  this.visits = this.visitsRef.snapshotChanges().map(changes => {
    return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
  });
});

This led to a console error as depicted below:

https://i.sstatic.net/ofZxv.png

Answer №1

Linking observables using switchMap allows them to execute sequentially.

this.dbAction.getDB().take(1)
    .switchMap(data => {
        this.userVisitOrder = data[0][this.currentUserID]['settings']['visitOrder'];

        this.visitsRef = afDatabase.list('data/users/' + this.currentUserID + '/visits/', ref => ref.orderByChild(this.userVisitOrder));

        return this.visitsRef.snapshotChanges();
    })
    .map(changes => {
        return changes.map(c => ({ key: c.payload.key, ...c.payload.val() }));
    });
    .subscribe(res => {// perform operations on result})

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

Displaying data in a table using NgFor and allowing the user to input the number of columns

My component has the capability to accept an array input, such as [1, 2, 3, 4, 5, 6, 7], and a number of columns input. For example, if a user specifies 3 columns, I want to display the data in a table with 3 columns like this: 1 2 3 4 5 6 7 If the ...

An effective way to pass an array as data to an express router from Angular

I've been attempting to retrieve more detailed information for multiple ID's from the database, but I've hit a roadblock. Below is the array of member ID's: var memberIds = ["2892056", "2894544", "2894545" ...

The constructor in Angular 2 service is operational, however, other functions within the service are experiencing issues

Here is the code I've been working on: This is the component.ts page code: import {Component, OnInit, NgModule, VERSION} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; import { UserService } from " ...

Tips for activating scrolling on a background element even with a modal window currently displayed

Encountering an issue with Angular and Material for Angular - my application contains multiple modals that disable background scrolling when opened. However, there is one notification modal that should not block the background scroll. Despite not having a ...

Encountered an ERROR when attempting to deploy a next.js app to Azure Static Webapp using GitHub actions for

I am encountering an issue that is causing some frustration. The problem only arises during my github actions build. Interestingly, when I run the build locally, everything works perfectly and I can access the route handler without any issues. However, eve ...

Discover the highest value within an array of objects, along with any numerical object attributes that have a value greater than zero

Considering an array of objects structured as follows: [{ "202201": { "WO": 900, "WS": 0, "SY": 0.915, "LY": 0.98, "CT": 75 }, "202202" ...

What is the best way to inform Angular2 RC1 about updates in the DOM?

Originally inspired by a discussion on Stack Overflow, this scenario presents a simpler use case. The issue at hand is how to inform Angular2 about externally added DOM elements that contain Angular directives. For example, adding a new button with a click ...

What is the best way to retrieve environment variables from an NPM package in an Angular 5 application

Is there a method for my node module, created from an Angular 5 application, to access the environment variable from the Angular 5 application (environments/environment.ts)? Perhaps Angular 5 exports its environment variables to JavaScript global variables ...

Angular auto suggest feature

I am working with a dropdown in Angular that contains JSON data. The data is stored in a List named options and I need to display the name field in the dropdown list. My current task involves implementing an autocomplete search feature for this dropdown. ...

Array updating using the foreach method in Angular

Hey everyone, I've encountered an error that seems to be related to scope and I could use some advice. I'm currently looping through an array and trying to push the results to another array. However, when I attempt to push the results to public m ...

Utilize an embedded Angular project to access a property file within a Spring Boot application

Currently, I am working on a project where Angular 6 is embedded within a Spring Boot application. Everything is running smoothly so far and the index.html file for my Angular app is located in the resources folder of the Spring Boot application. I am no ...

Displaying the component that was provided as a parameter

I am looking to develop a custom component that can take another component as a parameter and then embed it within an NgBootstrap modal while also incorporating additional HTML elements. I am unsure if this is achievable, but my goal is to enhance modals ...

How can you type a collection of initialized class instances in Typescript when given an object containing classes?

Imagine having an object that resembles the following: const typeMap = {category1: Category1, category2: Category2} In this case, Category1 and Category2 refer to classes, and there could potentially be hundreds of different categories. Now I also have a ...

What are the circumstances under which JavaScript GCP libraries return null values?

My current project involves working with GCP and Firebase using typescript. I have been utilizing the provided libraries, specifically version 8 of Firebase, and have encountered some unexpected behavior. For instance (firebase, ver. 8.10.1) import 'f ...

Unexpected behavior: Angular4/Javascript Date object alters when timezone is specified in Date constructor

In my Angular 4 application, I encountered an issue with a date retrieved from an API call. The date is in the format '1990-03-31T23:00:00-06:00' and when attempting to create a Date object and retrieve the month using getMonth(), it returns the ...

Encountering Issue: NG0303 - Unable to associate 'ng-If' as it is not recognized as a valid attribute of 'app-grocery'

NG0303: Encountering an issue with binding to 'ng-If' as it is not recognized as a valid property of 'app-grocery'. A similar problem was found here but did not provide a solution Despite importing CommonModule in app.modules.ts, I am ...

Optimal strategies for managing server-side validation/errors in Angular applications

Back in the day, I used to retrieve HTTP responses with a TypeScript object. validateTokenHttp(token: string): Observable<User> { return this.http.get<User>(`${environment.api}/auth/verifyToken/${token}`); } Sometimes it would return a Us ...

Sharing information between sibling modules

Currently, I am faced with the challenge of transmitting data between two sibling components within the following component structure. The goal is to pass data without changing the relationships between these components. I prefer not to alter the componen ...

Verify in typescript if type A is equal to either type B or type C

Within one specific file, there is a structured code block like the following: export const _total = { a: '', b: '', c: '', d: '', e: '', f: '', } type TotalKeysType = typeof _all; ex ...

Creating an Array in TypeScript

Is it possible to declare a global array in Typescript so that it can be accessed using "this" from any part of the code? In javascript, I would typically declare it as "var anArray=[]". What is the equivalent way of doing this in Typescript? Using anArra ...