Angular 2 Service返回对象对象

时间:2017-03-28 19:52:44

标签: angularjs node.js mongodb

感谢您提前的时间,我试图展示我从当地mongodb系列中提取的一个系列。 http://localhost:8080/player/all是API端点,当我使用postmaster测试它时返回正确的数据。它是一组对象。 HTML仅显示每个对象的[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],[object Object]

服务或组件有问题吗?

Backend是一个快速/节点应用

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());
  }
}

3 个答案:

答案 0 :(得分:1)

该变量包含一个对象列表。您正在UI中绑定对象/数组,因此它将[Object Object]称为其字符串表示

要获得所有值,您可以使用* ngFor并获取单个值并显示。

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

正如您所见

或者@saneetharan建议您可以通过索引值绑定侧数组中对象的个体属性

答案 1 :(得分:0)

当您在模板内显示时,您需要使用 dot 运算符访问属性,或者如果是数组,则使用ngFor。

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

答案 2 :(得分:0)

使用角管

{{allPlayers| json}}