Ionic3编码 - 试图检索当天的报价

时间:2018-01-05 15:49:10

标签: json ionic-framework ionic2 ionic3

provider.ts档案中的代码:

getQuotes() : Observable<any> {  
    return this.http.get(""); 
}

第一种方法:需要显示报价的页面的home.ts文件中的编码:

quote:string;
author:string;

constructor(public navCtrl: NavController, private qp: QuoteProvider) { }

ionViewDidLoad()
{
   this.qp.getQuotes().subscribe(data => {
      this.quote = data.quote;
      this.author = data.author;      
   });
}

.html代码尝试了这一点没有用:

<h2> {{ quote}} </h2>
<h3> {{ author }}</h3>
</ion-item>    </ion-list>

尝试了第二种方法;尝试使用数组虽然数据不是数组格式 home.ts档案:

export class HomePage {  quote:any[];  author:any[];    
constructor(public navCtrl: NavController, private qp: QuoteProvider) {  }

ionViewDidLoad() {
    this.qp.getQuotes().subscribe(data => {
       this.quote = data.quotes;
       this.author = data.quotes;
    });  
}

.html文件代码*:

<ion-list>
   <ion-item *ngFor = "let q of quote">

      <h2> {{ q.quote}} </h2>
      <h3> {{q.author }}</h3>
   </ion-item>    
</ion-list>

1 个答案:

答案 0 :(得分:2)

provider.ts中,您应该执行以下操作:

import 'rxjs/add/operator/map';

getQuotes(){
   return this.http.get("").map(res => res.json());

}

然后在home.ts

ionViewDidLoad()
{
  this.qp.getQuotes().subscribe(data => {
    this.quote = data.contents.quotes[0].quote;
    this.author = data.contents.quotes[0].author;   
    // This is assuming the quotes array always has only one quote
  });
}

修改
Prerak Tiwari注释时,您还需要删除home.html中的for循环:

<ion-list>
  <ion-item>
    <h2> {{ quote }} </h2>
    <h3> {{ author }}</h3>
  </ion-item>    
</ion-list>