繁体   English   中英

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

[英]How to display values in webpage using angular7

我从 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')
}

}

主页.component.html

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

数据服务.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 输出

ERROR CONTEXT Object { view: {…}, nodeIndex: 3, nodeDef: {…}, elDef: {…}, elView: {…} } HomeComponent.html:4 (3) […] 0: Object { firstname: "karthik", lastname: "selvam", id: 1 } 1: Object { firstname: "ranjith", lastname: "kumar", id: 2 } 2: Object { firstname: "sathish", lastname: "kumar ", id: 3 } 长度: 3

您的 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) { }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM