![](/img/trans.png)
[英]Angular 5 - unable to print rest json data by ngFor using ngOnIt
[英]Angular - Unable to print json data in HTML page using *ngFor
我是新手。 我創建了一個服務類,以json格式返回產品詳細信息。
api.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class ApiService {
constructor(private http: Http) { }
fetchData() {
return this.http.get('http://funiks.com/qbook/api/productmasterjson.php').map(
(response) => response.json()
).subscribe(
(data) => data
)
}
}
現在,我在組件類api.component.ts中調用了此服務
import { Component, OnInit } from '@angular/core';
import { ApiService } from '../api.service';
@Component({
selector: 'app-api',
templateUrl: './api.component.html',
styleUrls: ['./api.component.css']
})
export class ApiComponent implements OnInit {
public details;
constructor(private api:ApiService) { }
ngOnInit() {
this.details = this.api.fetchData();
console.log(this.details);
}
}
現在我想在HTML頁面中打印所有數據。 這就是我試圖打印json數據的內容
<tr *ngFor="let d of details">
<td>{{d.CATEGORY}}</td>
<td>{{d.HSN}}</td>
<td>{{d.ID}}</td>
<td>{{d.NAME}}</td>
<td>{{d.POSTINGHEAD}}</td>
<td>{{d.PRODUCTSERVICE}}</td>
<td>{{d.RATE}}</td>
<td>{{d.SACCODE}}</td>
<td>{{d.TAX_CONNECTED}}</td>
<td>{{d.TYPE}}</td>
<td>{{d.UNIT}}</td>
</tr>
但不幸的是,它拋出錯誤和錯誤就像
錯誤錯誤:找不到類型為“對象”的其他支持對象“ [對象對象]”。 NgFor僅支持綁定到Iterables,例如數組。
首先,您需要將public details
聲明為數組
public details: any[];
在異步請求返回任何內容之前,除非您指定模板,否則您對模板的details
的數據類型一無所知。
我認為這就是為什么您會收到這樣的錯誤。
找不到類型為“對象”的其他支持對象“ [對象對象]”。 NgFor僅支持綁定到Iterables,例如數組。
另外,將您的subscribe
部分放入組件代碼中
在您的ngOnInit
,您無需將返回值分配給this.details,因為在進行get調用時,請求將具有可觀察的訂閱。 您將獲得可觀察到的成功響應,因此設置this.details值需要成功,如下所示:
ngOnInit() {
this.api.fetchData().subscribe(response => this.details = response;);
console.log(this.details);
}
您的組件不知道fetchData
的類型,應使用fetchData():Observable<Product[]> {
您不應該在fetchData()
訂閱您的可觀察fetchData()
,只需返回可觀察對象
fetchData():Observable<Product[]> { return this.http.get('http://funiks.com/qbook/api/productmasterjson.php') .map((response) => response.json() ) }
在組件中,訂閱可觀察和輸入的details
details: Product[]; ngOnInit() { this.api.fetchData().subscribe(data => this.details = data); console.log(this.details); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.