我正在開發一個Angular2應用程序,我想用JSON文件中的http GET請求顯示一些JSON數據。 這是我的JSON(文件數據/ contatti.json):ngFor不打印JSON數據
[
"08823323459",
"3325849593",
"[email protected]"
]
我有一個從這個文件中請求數據的ContactService:
import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
@Injectable()
export class ContattiService {
private contactUrl = 'data/contatti.json';
constructor(private http: Http) { }
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
getContatti(): Promise<string[]> {
return this.http.get(this.contactUrl)
.toPromise()
.then(res => res.json().data as string[])
.catch(this.handleError);
}
}
有檢索使用該服務的數據的組件:
import { Component, OnInit } from '@angular/core'
import { ContattiService } from './contatti.service'
@Component({
selector: 'contact-app',
templateUrl: './contatti.html'
})
export class ContactComponent {
contatti: string[];
constructor(
private contactService: ContattiService) { }
ngOnInit(): void {
this.getContatti();
}
getContatti(): void {
this.contactService.getContatti().then(contatti => this.contatti = contatti);
}
}
但是當我嘗試在我的HTML頁面(contatti.html)來顯示他們:
<div class="col-sm-6">
<div class="panel panel-default">
<ul>
<li *ngFor="let contatto of contatti">
{{contatto}}
</li>
</ul>
</div>
</div>
頁面不打印數據。有人能幫助我嗎?
你試過從以.json文件中刪除'-quotes? – martennis
對不起,這是一個寫作問題的錯誤。他們沒有出現在我的代碼中。 – dona
在ng之前缺少'*'還有一個錯誤? –