Angular 2 Service 返回对象对象



提前感谢您的时间,我正在尝试显示我从本地mongodb收藏中提取的集合。http://localhost:8080/player/all 是 API 端点,当我使用邮局主管测试它时,它会返回正确的数据。它是一个对象数组。HTML 仅显示每个对象的 [对象对象],例如:

[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象],[对象对象

],[对象对象]

服务或组件有任何问题吗?

后端是一个快速/节点应用

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

使用角管

{{allPlayers| json}}

变量包含对象列表。您在 UI 中绑定对象/数组,因此它说 [对象对象] 作为其字符串表示形式

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

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

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

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

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

最新更新