如何使用angular7在网页中显示值

时间:2019-02-13 05:09:26

标签: java html mysql angular

我从API获得了值,并且可以在控制台日志中显示。但是我无法在网页上查看。我不知道我在那里做错了什么。谁能更新我如何实现并将值显示为html? home.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
 users: Object;

constructor(private data: DataService) { }

ngOnInit() {
this.data.getUsers().subscribe(data => {
    this.users = data
    console.log(this.users);
  }
);
}
 firstclick(){
  console.log('clicked button')
}

}

home.component.html

  <li *ngFor="let user of users.data">
    <p>
      {{ user.firstname }} 
    </p>
  </li>

data.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class DataService {

constructor(private http: HttpClient) { }

getUsers(){
    return this.http.get('http://localhost:3000/api/crs')
 }
}

console.log输出

错误上下文对象{视图:{…},nodeIndex:3,nodeDef:{…},elDef:{…},elView:{…}} HomeComponent.html:4(3)[…] 0:对象{firstname:“ karthik”,lastname:“ selvam”,id:1} 1:对象{firstname:“ ranjith”,lastname:“ kumar”,id:2} 2:2:Object {firstname:“ sathish”,lastname :“ kumar”,id:3}长度:3

1 个答案:

答案 0 :(得分:0)

您的API响应数据不包括数据字段包装器,因此请从html模板中删除数据 home.component.html

 <li *ngFor="let user of users">
    <p>
      {{ user.firstname }} 
    </p>
  </li>

在home.component.ts中 您可以更改用户属性的类型

export class HomeComponent implements OnInit {
 users: any[];

constructor(private data: DataService) { }