【问题标题】:Angular 2 Service returns object objectAngular 2 Service 返回对象对象
【发布时间】:2017-08-22 01:34:05
【问题描述】:

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

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

服务或组件有问题吗?

后端是一个 express/node 应用程序

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

【问题讨论】:

    标签: angularjs node.js mongodb


    【解决方案1】:

    该变量包含一个对象列表。您在 UI 中绑定对象/数组,所以它说 [Object Object] 作为它的字符串表示

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

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

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

    【讨论】:

      【解决方案2】:

      使用角管

      {{allPlayers| json}}
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

        • 谢谢。 ngFor 也返回 [object Object]。我想用对象显示数组,就像 API 返回它一样。
        • 你能发布你得到的数据是什么
        • [{"_id":"58d309f396c356946e700044","firstName":"LeBron","lastName":"James","overall":96,"position":"SF","salary":25,"duration":1,"notes":"Birdrechte","yearsInTeam":10,"team":"TOR","lastTeam":"","birthYear":1984,"age":32}] 这将是第一个对象。超过 500 个。
        • 答案有帮助吗?
        • 好的,谢谢。所以如果我想要整个对象,我必须对对象进行字符串化?
        猜你喜欢
        • 2017-08-25
        • 2016-10-13
        • 1970-01-01
        • 2015-03-24
        • 2021-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-30
        相关资源
        最近更新 更多