簡體   English   中英

如何以角度顯示從api獲取的數據

[英]How to display the fetched data from api in angular

從api提取的數據未顯示在屏幕上,但我正在控制台中獲取數據。

data.service.ts

    const httpOptions = {
      headers:new HttpHeaders({'Content-Type':'application/json'})
     };

    @Injectable()

    export class DataService {

    constructor(private http: HttpClient) {}
    getuserdetails(){
    return this.http.get<any> 
    ('http://jsonplaceholder.typicode.com/users/1')
    .pipe(map(item => {
        return item;
    }));
    }
   }

information.component.ts

 export class InformationComponent implements OnInit {
    dataItem:any = {} 

    constructor(private data: DataService) {
    this.data.getuserdetails().subscribe(item=>{
    console.log(item);
    this.dataItem=item;
  });
   }

  ngOnInit() {
  }

 }

information.component.html

<div *ngIf="dataItem?.length>=0">           
 <div *ngFor='let x of dataItem'>

   {{x.name}}

 </div>
 </div>

在這里,我正在控制台中獲取用戶1的詳細信息,但未在主屏幕上顯示。

嘗試將代碼放入ngOnInit

ngOnInit(){
 this.data.getuserdetails().subscribe(item=>{
  console.log(item);
  this.dataItem=item;
 });
}

並在html中進行驗證

<div *ngIf="dataItem">
   {{dataItem |json }}
</div>

您的*ngFor不能工作,因為它不是數組

我認為這應該有效。 constructor是打字稿的東西。 嘗試在Angular生命周期掛鈎中進行API調用

讓我們看看問題是什么:

首先,您嘗試獲取dataItem的長度,但它不是數組。 如果要檢查長度,請確保初始化dataItem像這樣dataItem = []

<div *ngIf="dataItem?.length>=0">           

其次,您嘗試在dateItem不是數組時對其進行迭代(循環)。 如果您按照上面的第一個項目符號所示進行初始化,則可以這樣做

 <div *ngFor='let x of dataItem'>

如果解決了這些問題,您將可以在模板中查看數據

看看這個作為工作示例https://stackoverflow-55772639.stackblitz.io

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM