2017-06-14 66 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