Issue
I would like to display the data from my JSON file.
Here is an idea of the information that is in the JSON => http://jsonblob.com/954388771009478656
In  DTA > PP , I just want to display the variable NOMFAMILLE.
I have an error message:
Cannot read properties of undefined (reading 'PP')
In HTML, I have this:
 <td class="text-center"> {{ dta.PP.NOMFAMILLE}} </td>
In TS,
dta ? : Dta;
private getDta(): void {
    let searchDta = new SearchDta(parseInt(this.registreNational + ''), parseInt(this.fiscalYear + ''), parseInt(this.country + ''));
    this.service.getDta(searchDta).pipe(
        takeUntil(this.unsubscribe$)
    ).subscribe(res => {
        if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
            this.dta = res.DTA;
            console.log("Data RES ");
            console.log(this.dta)
        }
    });
}
I did a console.log, I get the data.
Then...
search-dta.response.ts file
export interface SearchDtaResponse extends ApiResponse {
    DTA: Dta;
}
export interface Dta {
    PP:  PersonnePhysiqueDta;
    PTF_DTA: PortefeuilleDta[] 
}
export interface PortefeuilleDta {
    CLER: string;
    PAYS: number;
    EXERCICE: number;
    STATUTDTA: number;
    NUMEROSUIVI: number;
}
export interface PersonnePhysiqueDta {
    NOMFAMILLE: string; 
    NUMEROREGISTRENATIONAL: number;
    NATIONALITE: string;
}
search-dta.ts file
export class SearchDta {
    registreNational: number;
    fiscalYear: number;
    country: number; 
    constructor(
        registreNational: number = 0,
        fiscalYear: number = 0,
        country: number = 0, 
    ) {
        this.registreNational = registreNational;
        this.fiscalYear =  fiscalYear;
        this.country = country
    }
}
I don't understand why the PP object is not undefined?
Thank you for your help and your time
Solution
The data is being fetched asynchronously, so when the component renders the first time, then this.dta is undefined, hence the error. You can mitigate this by not rendering the td while the data is not there:
<td class="text-center" *ngIf="this.dta"> {{ dta.PP.NOMFAMILLE}} </td>
Or, you could even add an extra ng-content tag for the value itself and put the ngIf on that one (so that the table looks consistent)
<td class="text-center">
  <ng-content *ngIf="this.dta">{{ dta.PP.NOMFAMILLE}}</ng-content>
</td>
Another solution to this issue is to use the optional chaining operator ?.
<td class="text-center" *ngIf="this.dta"> {{ dta?.PP?.NOMFAMILLE}} </td>
Answered By - Octavian Mărculescu
 


0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.