Angular 8 is encountering an issue with an undefined global variable, specifically the variable "this

I have a model named Chat, defined as follows:

export class Chat {
chatId?: number;
chatUser1?: string;
chatUser2?: string;
chatStatus?: string;
created_at?: any;
updated_at?: any;
deleted_at?: any;

}

In the component, I need to retrieve the value of chatUser2 with a specific criteria. To achieve this, I created an array named chats for instances of the Chat model.

chats: Chat[];

Then, I implemented the following function:

getChats(): void { 
this.loadingChats = true;

this.chatService.getChats().subscribe((data: any[]) => {
  this.chats = data;
});

this.toCall = true;
this.toAnswer = false;
this.toHangUp = false;
var status = "true";

var chatUser2 = [];
var chatStatus = [];
var chatChannel = [];

chatUser2 = this.chats.map((v) => v.chatUser2);
chatStatus = this.chats.map((v) => v.chatStatus);
chatChannel = this.chats.map((v) => v.chatId.toString());

var size = chatUser2.length;

for (var i = 0; i < size; i++) 
{
  console.log(i.toString());
  if (chatUser2[i] === this.userName && chatStatus[i] === status) 
  {
    this.toAnswer = true; 
    this.toCall = false;
    this.toHangUp = false;
    this.channel = chatChannel[i]; 
    console.log("break");
    break;
  }
}

However, an error is being displayed in the console - ERROR TypeError: "this.chats is undefined" at :

chatUser2 = this.chats.map((v) => v.chatUser2);

Your assistance is greatly appreciated.

Answer №1

When dealing with chatService.getChats(), which is an observable asynchronous operation, it is important to wait for its completion. One way to handle this is by utilizing async/await in your code.

async getChats(): Promise<void> { 
this.loadingChats = true;

this.chats = await this.chatService.getChats().toPromise();

this.toCall=true;
this.toAnswer=false;
this.toHangUp=false;

var status="true";
var chatUser2 = [];
var chatStatus = [];
var chatChannel = [];

chatUser2 = this.chats.map((v)=>v.chatUser2);
chatStatus = this.chats.map((v)=>v.chatStatus);
chatChannel = this.chats.map((v)=>v.chatId.toString());

var size = chatUser2.length;

for(var i=0; i<size ; i++) 
{
  console.log(i.toString());
  if(chatUser2[i] === this.userName && chatStatus[i]===status) 
  {
    this.toAnswer=true; 
    this.toCall=false;
    this.toHangUp=false;
    this.channel=chatChannel[i]; 
    console.log("break");
    break;
  }
}

Alternatively, you can integrate your code within the body of the subscribe method like below:

getChats(): void { 
this.loadingChats = true;

this.chatService.getChats().subscribe((data: any[]) => {
  this.chats = 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

The immutability of TypeScript's `as const` compared to JavaScript's Map object

Let's delve into a straightforward example: const simpleObject = { one: 'one', two: 'two', three: 'three' } Historically, pre ES2015 objects did not guarantee the preservation of key order upon retrieval. However, ...

The proper method for retrieving FormData using SyntheticEvent

I recently implemented a solution to submit form data using React forms with the onSubmit event handler. I passed the SyntheticBaseEvent object to a function called handleSubmit where I manually extracted its values. I have identified the specific data I n ...

"Embracing the Power of Font Awesome 5 in Angular 5

After using the font-awesome npm package (which is Font Awesome 4.7 version), I decided to upgrade to Font Awesome 5. In order to make this transition, I installed the following packages: "@fortawesome/angular-fontawesome": "^0.1.1", "@fortawesome/fontawe ...

Tips for notifying the user about incorrect login credentials in Ionic 3

I'm attempting to implement a notification system using showAlert to inform users when they enter an incorrect email or password, but I'm having difficulty achieving this using try and catch statements Would it be feasible for me to use try and ...

How should I proceed when encountering a TypeScript error stating "Object may be null"?

Within the compilerOptions section of my tsconfig.json configuration file, I have enabled the strictNullChecks setting to true. Every now and then, when utilizing functions such as getElementById("...") or querySelector("..."), a non-fatal warning pops up ...

Transferring information from child to parent class in TypeScript

I have a scenario where I have two classes (Model). Can I access properties defined in the child class from the parent class? Parent Class: class Model{ constructor() { //I need the table name here. which is defined in child. } publ ...

Issue with Angular Material Auto Complete not selecting items when filtered

Encountered a problem with the mat-autocomplete control in Angular Material where it fails to include the CSS class "mdc-list-item--selected" on the mat-option and also does not add the mat-pseudo-checkbox to a selected option when the contents are display ...

Having difficulties in accessing an API with Ionic 3

Whenever I attempt to connect with an API, I keep encountering the Cross-Origin Read Blocking (CORB) blocked cross-origin response error. Can anyone provide guidance on how to resolve this issue? Any assistance would be greatly appreciated. ...

Can TypeScript ascertain the object's type dynamically based on the key of its proxy name?

I am creating a wrapper class that will handle various operations related to the user entity. These operations include checking if the user is a guest, verifying their permissions, and more. One of the functions I want to implement in this class is an acce ...

Angular 9 Event Emitter fails to trigger a signal

I am currently working on passing data from a form-component to a modal-component using Event Emitter. Below is the configuration I have set up for this - Form.ts @Output() userEmail = new EventEmitter; submit(order): void { this.userEmail.emit(order.va ...

Having trouble activating the ENTER key press event listener for the QuillJS editor in Angular 4 and above

I have been trying to set up an event listener for the ENTER key press in QuillJS using addBinding as described in the official documentation here. However, despite successfully configuring listeners for other keys like BACKSPACE, I am unable to get the EN ...

*ngFor failing to refresh data after receiving server response

After utilizing Knockout for the past 5 years, I have decided to dive into the latest version of Angular for a change. Therefore, I am relatively new to Angular. Problem Upon clicking, a server call is executed which performs certain actions and returns ...

Ensuring Proper HTTP Content-Type Header In Angular2: Safari's Special Requirements

I have integrated the Dropbox HTTP API into my Angular2 App for logging in, authorizing, and making requests such as list_folder, which all function properly. However, when attempting to make a simple POST request to files/download, I encountered an error ...

Saving a picture to your Ionic device

I am currently using the code snippet below to access the device's Photo Library. However, it is returning a base64 encoded string, which has left me feeling unsure of how to proceed with this information. My goal is to save the photo to the applicati ...

Unable to locate the identifier 'Annotorious'

Currently utilizing NextJS with TypeScript The following script has been added: <Head><link href="/css/bindingbox.min.css" rel="stylesheet"></link><script async type="text/javascript" src="/scripts/an ...

Authenticating passports without the need for a templating engine

Seeking assistance with integrating Passport authentication using the Google strategy. Authentication with Google works, but upon returning to the express server, I aim to redirect to a client-side page along with profile data without utilizing a templatin ...

Ways to showcase multiple entities on the "home.component.html" page using JHipster?

I am looking to showcase two different types of items(product, recipe) on the main page in my jhipster application. How can I make this happen? Home.route.ts @NgModule({ imports: [MyappSharedModule, RouterModule.forChild([HOME_ROUTE]), JhpbackE ...

Is there a way to implement several filters on an array simultaneously?

Is it possible to filter an array based on both the input text from the "searchTerm" state and the selected option from the dropdown menu? I am currently using react-select for the dropdown functionality. const Positions = ({ positions }: dataProps) => ...

Apologies, but there was an error attempting to differentiate 'nombreyo'. Please note that only arrays and iterables are permitted for this action

Encountering an error while attempting to display a class in the HTML. <li> <ul> <li *ngFor="let refac of refactormodel" > -- word_to_rename: {{refac.word_to_rename}} -- renowned_word: {{refac.renowned_word}} ...

Obtaining attribute data value upon selection change in Angular 4

Having trouble retrieving the value from data-somedata in my code... <select class="form-control input-sm" [(ngModel)]="o.id" formControlName="optionals" (change)="menuChange($event)"> <option *ngFor="let menu_optional of menu_optionals" value= ...