2017-02-19 77 views
1

我試圖調用與ionic2的API,數據提供程序看起來像this.the服務返回對象數組。當我提供應用程序時,數據不顯示在HTML模板中。我如何解決這個問題。API調用與ionic2問題

import { Injectable } from '@angular/core'; 
    import { Http } from '@angular/http'; 
    import 'rxjs/add/operator/map'; 


    @Injectable() 
    export class VideoService { 
    videos: any; 


    constructor(public http: Http) { 
    console.log('Hello videoService Provider'); 
    } 

    getVideos(){ 
    this.http.get('http://mizikjams-lorisson.rhcloud.com/api/videos.json') 
    .map(res => res.json()).subscribe(data => { 
    this.videos= data.videos; 
    console.log(this.videos); 
    }); 

    } 


    } 

這裏的HTML模板代碼

<ion-content class=" mainpage card-background-page "> 
    <ion-list> 
    <ion-item *ngFor="let video of videos"> 
    <ion-avatar item-left> 
    <img src="{{video.image}}"> 
    </ion-avatar> 
    <h2>{{video.title}}</h2> 
    </ion-item> 
    </ion-list> 
    <div class="floatingbtn"> 
    <ion-fab bottom right edge > 
    <button ion-fab color="orange" (click)="search();"><ion-icon name="search"></ion-icon></button> 
    </ion-fab> 
    </div> 
    </ion-content> 
+0

看起來你看過 「視頻」,並讓他們在服務。你有沒有使用這項服務的組件?和這個HTML代碼,它是否附加到任何組件/頁面? – MorKadosh

回答

1

看到工作plunker - http://plnkr.co/edit/JtLm3K?p=preview

確保您的提供程序添加到app.module

@NgModule({ 
    imports: [ IonicModule.forRoot(AppComponent) ], 
    declarations: [ AppComponent, HomePage ], 
    entryComponents: [ HomePage ], 
    bootstrap: [ IonicApp ], 
    providers: [VideoService] 
}) 
export class AppModule { } 

提供商

import { Injectable } from '@angular/core'; 
    import { Http } from '@angular/http'; 
    import 'rxjs/add/operator/map'; 


    @Injectable() 
    export class VideoService { 
    videos: any; 


    constructor(public http: Http) { 
    console.log('Hello videoService Provider'); 
    } 

    getVideos(){ 
    return this.http.get('http://mizikjams-lorisson.rhcloud.com/api/videos.json') 
    .map(res => res.json()); 

    } 


    } 

page1.ts

import { Component } from '@angular/core'; 
import { NavController } from 'ionic-angular'; 
import { VideoService } from './videoService' 

@Component({ 
    selector: 'page-home', 
    templateUrl: 'app/home.page.html' 
}) 
export class HomePage { 

    appName = 'Ionic App'; 
    videos:any 

    constructor(public navController: NavController, public vs : VideoService) { 

    this.videos = this.vs.getVideos() 
    } 

} 

HTML

<ion-header> 
    <ion-navbar> 
    <ion-title>{{ appName }}</ion-title> 
    </ion-navbar> 
</ion-header> 

<ion-content padding> 
    <ion-list> 
     <ion-item *ngFor="let video of (videos | async)?.videos "> 
     <ion-avatar item-left> 
      <img src="{{video.image}}"> 
     </ion-avatar> 
     <h2>{{video.title}}</h2> 
    </ion-item> 
    </ion-list> 
</ion-content> 
+0

感謝您的及時回覆,我修改了代碼,仍然沒有在html模板中顯示數據。但是當我console.log它,我看到控制檯中的所有對象。但它不出現在html模板中。 –

+0

終於它的工作,我不得不改變一些事情。 –