[英]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.