Home > Software engineering >  Angular Function returning Undefined
Angular Function returning Undefined

Time:10-16

Hello I find myself confused as to why my console log is coming back undefined in Angular. Im am trying to display data on a card in html. The plan was to wire whatever data was coming in and display it through cardValue

HTML

 <mat-card >
    <mat-card-subtitle><b>Value:</b> {{ item.cardValue }}</mat-card-subtitle>
  </mat-card>

Service.ts

 incomingData(): Observable<any> {
    return this.httpClient.get<any>('this_is_incoming_data/', {});
  }

Component.ts

cardDetails = [
    {
     cardValue: console.log('this is test 3, 'this.custom()),
    }


returnedData: any;

ngOnInit(): any {
  this.Service.incomingData().subscribe((data: any) => {
    this.returnedData = data;
    console.log('test1',this.returnedData);
    this.custom();
  });
} 


custom(): any {
    const placeholder = "hello"
    return placeholder 
}
cardValue: {Name: John, Size: Medium, Age: 34}

on the console.log for test 1-3 logs perfectly fine & as expected but when I change custom() to need the card value like so.

custom(): any {
  const placeholder = this.returnedData.cardValue] 
  return placeholder
}

test 3 returns undefined and gives me an error Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'cardValue')

I know that the issue is in custom function but I do not know what to change it to get it to work

CodePudding user response:

Following code runs before ngOnInit. this.returnedData is set in ngOnInit, and hence it throws error for this.returnedData.cardValue as returnedData is undefined.

cardDetails = [
    {
     cardValue: console.log('this is test 3, 'this.custom()),
    }

Change your custom code to as below. This will ensure if returnedData is not set, placeholder is empty otherwise card value of returned data.

const placeholder = this.returnedData? this.returnedData.cardValue : '';

CodePudding user response:

Issue of undefined is because of asyncronous thread of observeable please modify your custom() method by accepting an argument when data received

    ngOnInit(): any {
  this.Service.incomingData().subscribe((data: any) => {
    this.returnedData = data;
    this.custom(this.returnedData.cardValue);
  });
} 


custom(value): any {
    const placeholder = value
    return placeholder 
}
  • Related