2016-10-02 45 views
1

我正在使用Ionic 2 Calendar來顯示已從遠程服務器訂閱爲json的課程時間。我試圖從我的訂閱中提取響應並將其放入數組,但是當將數據輸出到console.log時,我得到「未定義」。如何從角度提取數據http.get.subscribe

的代碼如下:

export class Calendar { 
    eventSource; 
    viewTitle; 

    constructor(private navController:NavController, private httpService:HttpService) { 
     var classes = []; 
     this.httpService.getCalendarConfig() 
      .subscribe(res => classes => res); 

     console.log(classes); 
    } 

注意,如果我改變.subscribe到:

.subscribe(res => console.log(res)); 

它顯示了JSON,因爲它應該在控制檯中。

編輯:HTTPService類如下所示:

@Injectable() 
export class HttpService { 

    endpointUrl:string = '<address>'; 

    constructor(private http: Http) {} 

    getCalendarConfig() { 
     return this.http.get(this.endpointUrl + 'calendar.json') 
         .map(this.extractData) 
         .catch(this.handleError); 
    } 

    private extractData(res: Response) { 
     let body = res.json(); 
     return body || {}; 
    } 

    private handleError(error: any) { 
     let errMsg = (error.message) ? error.message : 
      error.status ? '${error.status} - ${error.statusText}' : 'Server error'; 
     console.error(errMsg); 
     return Observable.throw(errMsg); 
    } 

}

回答

2

因爲你正在考慮classes價值,只要您對服務的調用適用。但這不適用於異步調用的方式。只要ajax完成,他們將始終提供輸出。

你會得到內部this.httpService.getCalendarConfig()

var classes = []; 
this.httpService.getCalendarConfig() 
    .subscribe(res => { 
     classes => res; 
     console.log(classes); 
    }); 
+0

嗨@Pankaj Parkar認購的成功classes對象,謝謝你,已改善了這種情況,是因爲它不再說「不確定」。但是現在控制檯說:Array []。我是否分配了錯誤的數據類型? –

+0

您可以打開該陣列..你會得到它的元素 –

+0

嗨@Pankaj抱歉的延遲!你如何打開陣列? –