如何在角度UI上显示[object Object]?

时间:2019-06-30 05:57:37

标签: node.js angular

我试图在有角度的UI上显示我的后端api http://localhost:3000/api/radar_life_cycle的响应,但是不知何故我将输出显示为[object Object],响应上的console.log显示了正确的对象,但未显示在UI,我缺少什么?有关如何在UI上显示对象的任何指导?

html

<textarea rows="6" [(ngModel)]="enteredValue"></textarea>
<hr>
<button (click)="get_radar_lifecycle_data()">Search</button>
<p>{{newPost}}</p>

component.ts

import { Component, OnInit, Injectable } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { Subject } from "rxjs";
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-radar-input',
  templateUrl: './radar-input.component.html',
  styleUrls: ['./radar-input.component.css']
})


export class RadarInputComponent  {

constructor(private http: HttpClient) {}
newPost = '';
get_radar_lifecycle_data(){
     this.http.get('http://localhost:3000/api/radar_life_cycle',{params:this.enteredValue}).subscribe(response => {
     console.log(response);
      this.newPost = response
      });
}

}

响应:-

{message: "Posts fetched successfully!", posts: Array(1)}

当前输出:-

enter image description here

3 个答案:

答案 0 :(得分:2)

您可以使用Angular内置的JSON管道,该管道包含在@angular/common中,并通过BrowserModuleCommonModule导入:

<textarea rows="6" [(ngModel)]="enteredValue"></textarea>
<hr>
<button (click)="get_radar_lifecycle_data()">Search</button>
<p>{{newPost | json}}</p>

有关管道的更多信息,请查看JsonPipe API。

答案 1 :(得分:2)

通过引用{message: "Posts fetched successfully!", posts: Array(1)}

您可以使用*ngFor来显示数组,如下所示:

<div *ngFor="let item of newPost?.posts">
   {{ item.milestone }} 
</div>

或显示属性:

{{ newPost?.message }}
  

编辑:

更改:

newPost = '';

收件人:

newPost: any;

并且您已经可以访问该数组的对象,因此您只需要执行以下操作:

{{ item.milestone }}

Working Demo

答案 2 :(得分:2)

您需要通过json pipe

检查对象结构

通过ngFor显示对象属性,因为结果返回Array

https://stackblitz.com/edit/angular-d17ggk