Search code examples
angularjstypescriptundefined

Typescript object property 'undefined' while it is not


I'm farly new with Typescript and struggle with what seems to be a dumb issue:

I retrieve an 'agent' object from a service.

this.agentsController.getAgent(matricule).subscribe({
      next: agent => {
        console.log(agent)
        console.log(agent.emailPro)
      },
      error: (error: string) => {
        console.log(error)
      }
    });

According to the 1st console.log, it is well populated :

{
    "agent": {
        "matricule": "000001",
        "nom": "DummyName",
        "prenom": "DummyFirstname",
        "emailPro": "dummy@dummy.fr",
        "adresse1": "dummy address",
        "telephonePerso": "0000000001"
    }
}

But as clearly as the print of the agent shows a well defined email address (emailPro), the 2nd console.log always shows undefined

How is that possible ? What am I missing ?


Solution

  • To summaries the comments chain as a valid response :

    My service was encapsulating my proper agent object in some other dummy object that happens to be called 'agent' as well. Hence the confusion !

    So instead of calling agent.EmailPro I should have called agent.agent.EmailPro.

    I chose to fix my service instead so it parsed the API response better :

    From this.httpClient.get('apiUrl').pipe(map((result:any) => result as Agent));

    To this.httpClient.get('apiUrl').pipe(map((result:any) => result.agent as Agent));

    Thanks again to @pietro909 & @T.J.Crowder