Home > Enterprise >  Angular Http Get request return Array(2)[Object, Object] but undefined
Angular Http Get request return Array(2)[Object, Object] but undefined

Time:09-30

I want to thank you in advance for your help. The point of the project is to have a .net core rest api and the UI in angular that communicate.

Currently the api works: send an array of two objects of type Member ([Member_0, Member_1]) and is called by the get request from Angular. http://localhost:61236/api/Members

[{"id":0,"lastname":"V","firstname":"D","dateOfBirth":"00/01/1789"},{"id":1,"lastname":"C","firstname":"M","dateOfBirth":"01/02/1789"}]

But that's what is showed in the explorer (with angular): Two undefined objects... and I don't know what is wrong. I've seen a lot of questions about it but no answer that works for me. Explorer view

Rest Api Code:

 [ApiController]
[Route("api/[controller]")]
public class MembersController : ControllerBase
{
    // GET : Members
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Member>>> Get()
    {
        var task = Task.Factory.StartNew(() =>
            {
                return MembersJsonProcessor.Deserialize(nameof(Members).ToString());
            });
        await task;
        if (task.Result == null) { return NotFound(); }
        return Ok(task.Result.MembersList.ToArray());
    }
}

Member service:

export class MembersComponentService {

readonly baseURL = "http://localhost:61236/api/Members"

constructor(
private http: HttpClient,
private  messageService: MessageComponentService) {}

httpOptions = {
  headers: new HttpHeaders({ 
    'Content-Type': 'application/json'
    })
};

getMembers() : Observable<Member[]> {
    return this.http.get<Member[]>(this.baseURL, this.httpOptions)
      .pipe(              
        map((response : Member[]) => {
          // var result : Member[] = [];           
          // response.forEach(member => {
          //   result.push(member);
          //   this.log(member.Firstname);
          // });
          this.log("Firstname: "   response[0].Firstname); // return 
          Undefined
          return response;
        }),
          tap((response) => {
            this.log('fetched members');
            this.log(response.length.toString());
          }),
          catchError(this.handleError<Member[]>('getMembers Error!', []))
      );
   }
 }

Member Component:

export class MembersComponent implements OnInit {
members: Member[];

constructor(private service: MembersComponentService,
private  messageService: MessageComponentService) {
  this.members = [];
 }

ngOnInit() {
this.getMembers();
}

getMembers() {
this.service.getMembers().subscribe((response: Member[]) => {
  // this.members = [
  //   {Id:0, Firstname:"D", Lastname:"V", DateOfBirth:"00/01/1789"},
  //   {Id:1, Firstname:"M", Lastname:"C", DateOfBirth:"01/02/1789"}
  // ];
  this.members = response;

});
}
/** Log a HeroService message with the MessageService */
private log(message: string) {
  this.messageService.add(`MemberComponent: ${message}`);
}

}

Member Component html:

<h2>Members</h2>
<button (click)="getMembers()">Refresh</button>
<hr/>
<ul class="members-list">
<li *ngFor="let member of members" class="app-members">
    <span>Id: {{member.Id}}</span>
    <span>Firstname: {{member.Firstname}}</span>
    <span>Lastname: {{member.Lastname}}</span>
    <span>DateOfBirth: {{member.DateOfBirth}}</span>
</li>  
</ul>

CodePudding user response:

Your data :

{"id":0,"lastname":"V","firstname":"D","dateOfBirth":"00/01/1789"}

What you are trying to access :

{{member.Id}}
{{member.Firstname}}
{{member.Lastname}}
{{member.DateOfBirth}}

None of the variables in your template match your data structure. It should be :

{{member.id}}
{{member.firstname}}
{{member.lastname}}
{{member.dateOfBirth}}

CodePudding user response:

Just check your interface Member[]. Is it same as response?

CodePudding user response:

The problem is in the this.log("Firstname: " response[0].Firstname); code. The response is an object below, which is not iterable. You should rather log response.user[0].firstname (check the lowercase/uppercase as well)

{
    "success": true,
    "user": [{
        "id": 0,
        "lastname": "V",
        "firstname": "D",
        "dateOfBirth": "00/01/1789"
      },
      {
        "id": 1,
        "lastname": "C",
        "firstname": "M",
        "dateOfBirth": "01/02/1789"
    }
   ]
 }

Log the whole response object to see its properties, hence determine which ones you would want to map

  • Related