2017-06-14 75 views
1

我正在開發一個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> 

頁面不打印數據。有人能幫助我嗎?

+0

你試過從以.json文件中刪除'-quotes? – martennis

+0

對不起,這是一個寫作問題的錯誤。他們沒有出現在我的代碼中。 – dona

+0

在ng之前缺少'*'還有一個錯誤? –

回答

0

你應該重寫你的方法與訂閱:

getContatti(): void { 
    this.contactService.getContatti() 
    .subscribe(contatti => this.contatti = contatti); 
} 

和服務:

getContatti(): { 
    return this.http.get(this.contactUrl) 
     .map(res => res.json().data) 
     .catch(error => this.handleError(error)); 
    } 

還有一,如果您嘗試訪問res.json()數據的contatti.json應該是這樣:

{ 
    "data": [ 
    "08823323459", 
    "3325849593", 
    "[email protected]" 
    ] 
} 
+0

是的Korotkikh,您的解決方案的作品!非常感謝! – dona

+0

不客氣! ;) –

+1

說實話,只是需要改變JSON文件,就像你建議讓我的代碼工作一樣! :) – dona

0

試試這個組件裏面,

getContatti(): void { 
    this.contactService.getContatti().subscribe(contatti=>{ 
     this.contatti = contatti; 
    }); 
} 

和service.ts應該是,

getContatti(): { 
    return this.http.get(this.contactUrl) 
     .map(res => res.json().data) 
     .catch(error => this.handleError(error)); 
    } 
+0

謝謝@Sajeetharan,但我不明白你的代碼中應該是this.newService。 – dona

+0

它應該是contactService – Sajeetharan