MFKGER
MFKGER

Reputation: 35

Angular 2 Service returns object object

thank you for your time in advance, I'm trying to display a collection I pulled from a local mongodb collection. http://localhost:8080/player/all is the API endpoint which returns the right data when I test it with postmaster. It's an array of objects. The HTML only shows [object Object] for each object like:

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

Is there any problem with the service or the component?

Backend is an express/node app

player.component.html

<div> {{allPlayers}} </div>

player.component.ts

import { Component, OnInit } from '@angular/core';
import {AuthService} from '../../services/auth.service';
import {PlayerService} from '../../services/player.service';
import {Router} from '@angular/router';

@Component({
  selector: 'app-player',
  templateUrl: './player.component.html',
  styleUrls: ['./player.component.css']
})
export class PlayerComponent implements OnInit {
  allPlayers: Array<Object>;


  constructor(private authService:AuthService,
              private router:Router,
              private playerService: PlayerService) { }

  ngOnInit() {
    this.playerService.getAllPlayers().subscribe(allPlayers => {
      this.allPlayers = allPlayers;
    },
    err => {
      console.log(err);
      return false;
    });
  }
}

player.service.ts

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class PlayerService {


  constructor(private http:Http) {

 }

  getAllPlayers(){
    return this.http.get("http://localhost:8080/player/all")
        .map(res => res.json());
  }
}

Upvotes: 3

Views: 13930

Answers (3)

Aniruddha Das
Aniruddha Das

Reputation: 21688

The variable holds a list of objects. You are binding the object/array in the UI so it's saying [Object Object] as its string representation

To get all the values you can use *ngFor and get individual value and show.

<ul>  
  <li *ngFor="#player of allPlayers">
    {{ player.name }} is {{ player.age }}.
  </li>
</ul>  

Or as @saneetharan suggested you can bind individual properties of the objects in side array by there index values.

Upvotes: 3

srinivassree
srinivassree

Reputation: 129

use angular pipe

{{allPlayers| json}}

Upvotes: 4

Sajeetharan
Sajeetharan

Reputation: 222582

You need to access the properties using dot operator when you are displaying inside the template, or use ngFor if its an array.

 <div *ngFor="let player of allPlayers">
  {{player.firstName}}
 </div>

Upvotes: 2

Related Questions