What causes an undefined variable error even after assigning a value in the constructor?

Struggling with accessing a variable called this.currentLang that is assigned a value in the constructor, but remains undefined within the displayIndustries method. I've tried defining it as both a boolean and a string outside of the constructor, yet the issue persists. Any ideas on what could be causing this scope problem?

Answer №1

The variable in the constructor is not being utilized. Instead, it is used inside a subscription callback that occurs asynchronously either after or during the constructor call. To prevent currentLang from becoming undefined, you can initialize it.

  currentLang = ''

  constructor(
       private fb: FormBuilder, 
       private langService: LangService ,
       private translate: TranslateService
  ) {

    this.langService.currentLang.subscribe((lang) => {
      this.currentLang = lang;
      this.showCurrentLang = this.currentLang === 'en';
      if (this.AfterDisplayIndustries) {
        this.displayIndustries();
      }
    });
  }


  displayIndustries (industry?: IIndustry) {
    this.AfterDisplayIndustries = true;
    return (this.currentLang === 'en' && industry) ? industry.name : industry.nameCZ;
  } 

(Your code has also been made more concise)

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

Why are other elements not appearing on the index.html page when <app-root> is not included?

Just started delving into Angular and following some tutorials. The project was set up using Angular CLI. Created a new component named navbar on top of the default component and wanted to check if the navbar loads in the index.html at startup. The navbar ...

What is the best way to convert an array received from an @Output emitter into a formGroup with formControls in Angular reactive forms?

In the past, I have been able to initialize a form array of form controls when the array value is available during onInit. However, the situation is different this time. The array value will be received from the output of my child component only. parentco ...

Encountering an Issue: "ng new" Command Throws Error Upon Creating Angular Project

I am encountering an issue while using ng new project_name: The error message states "An invalid configuration file was found ['angular.json']. Please delete the file before running the command." I am stuck on this problem and unsure of how to ...

Having trouble establishing a default value for Material Multiselect in Angular 6

I am currently attempting to incorporate a multiselect feature in an Angular application using Material design. However, I am encountering an issue where the default selected types are not working as expected when the page is opened in Edit mode. Displaye ...

Access-Control-Allow-Methods is not permitting the use of the DELETE method in the preflight response for Angular 2

I am having trouble deleting a record in mongodb using mongoose. Here is the code snippet from my component: deleteProduct(product){ this._confirmationService.confirm({ message: 'Are you sure you want to delete the item?', ...

Steps to improve the appearance of the Header on a dataTable during Dragging

I am working on creating a table that can be reordered using mat-table and MatTableDataSource. However, I would like the column to have a white background color instead of being transparent when dragged. Is there a way to achieve this? <table mat-tab ...

Struggling to grasp the process of incorporating OAuth into both a REST API and a Single Page Application

I am currently working on integrating my SPA, DjangoRestframework, and auth0. My understanding is that the user registration process, as well as logging in and out, are all handled by Angular. Here are some key questions I need assistance with: 1. Aft ...

"Typedoc indicates that no entry points were detected"

This is my main.ts file, but I had renamed it to index.ts later. However, I still encountered the same error multiple times as shown in the terminal output below: https://i.sstatic.net/hFHmX.png Below is the content of my tsconfig.json file: https://i.s ...

Cannot proceed with module import: Type 'ModuleWithProviders<T>' must have a single type argument

ERROR in node_modules/@angular/fire/firestore/firestore.module.d.ts:7:74 - error TS2314: Generic type 'ModuleWithProviders<T>' requires 1 type argument(s). 7 static enablePersistence(persistenceSettings?: PersistenceSettings): ...

How can I create a computed field in TypeORM by deriving its value from other fields within the same Entity?

My goal is to implement a 'rating' field in my User Entity. Within the User Entity, there exists a relationship with the Rating Entity, where the User has a field called ratingsReceived that eagerly loads all Ratings assigned to that User. The & ...

Separate your HTML code and move it to a different HTML document within Angular CLI

Is there a way to extract my HTML section from the file app.compontent.ts and place it in a separate HTML document? I've tried adding the HTML code directly into the generated class app.component.ts but it doesn't seem to work. I'd also lik ...

How to seamlessly incorporate Polymer Web Components into a Typescript-based React application?

Struggling to implement a Polymer Web Components tooltip feature into a React App coded in TypeScript. Encountering an error during compilation: Error: Property 'paper-tooltip' does not exist on type 'JSX.IntrinsicElements' To resolve ...

Combining Typescript and React to create a conditional callback prop type depending on whether an optional prop is

In my react component, I have the option to pass an optional prop called isSingle (boolean) and a required prop called onSelect (callback). If the isSingle prop is used, I want the callback to have a different signature. type CustomProps<T> = { ...

Locate the nearest upcoming date and time to today's date in the JSON response

I am currently working with an API that provides a response containing the `start_time` field in JSON format. My goal is to extract the ID from the JSON object whose next date time is closest to the current date and time, excluding any dates from the past. ...

Angular application encountering a 401 unauthorized error when attempting to connect to TFS API

Having trouble with an API get request in my initial Angular project. I'm attempting to retrieve all projects from a server using the correct URL (which works in Postman and my browser), as well as a token generated from my TFS account. Despite this, ...

How can I set up server-side rendering in Laravel using Angular?

For my single page application built with Angular 5, I decided to integrate it with a Laravel backend. In the Laravel project, I stored all my Angular files within an 'angular' folder. However, I built the actual Angular application outside of th ...

Updating the array in React state does not work properly

Update: Visit the Snack Expo for the latest version. I have a page that displays a list. When I click on a Delete button, my goal is to remove the item with a specific id from the list. The code snippet is shown below: import { useState, memo, useCallbac ...

Steps for creating a TypeScript project for exporting purposes

Forgive me for my lack of experience in the js ecosystem. Transitioning from static languages to typescript has been a positive change, though I still find myself struggling to grasp the packaging/module system, especially when coupled with typescript defi ...

What is the best way to include a query string in Angular without affecting the browser's navigation history?

In my Angular application, the user's selection of a match percentage triggers an update to the URL with new query string parameters specific to that value. To achieve this functionality, I am using the following code snippet. However, one drawback i ...

Strategies for excluding a union type based on the value of a field

I have this specific type structure (derived from a third-party library): type StackActionType = { type: 'REPLACE'; payload: { name: string; key?: string | undefined; params?: object; }; source?: string; ...