我可能只是在某個地方犯了一個愚蠢的錯誤,但我只是不再看到它。Ionic 2 Angular 2獲取REST JSON數據
我有一個非常簡單的Ionic 2 Angular 2應用程序。請不要打擾這個架構,我只是想先讓它工作。我正嘗試用我從REST JSON服務中獲得的Module對象填充我的數組''configuredModules'。我創建了一個將數組記錄到控制檯的按鈕,所以我可以看到數組的值是什麼,但始終未定義。我究竟做錯了什麼?
export class Module {
type: string;
physicalLocationName: string;
}
和我的主類:
import { Component, OnInit } from '@angular/core';
import { Module } from './module';
import { HttpModule, Http, Response} from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/toPromise';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage implements OnInit{
configuredModules: Module[];
http: Http;
constructor(public navCtrl: NavController,private _http: Http) {
this.http = _http;
}
getConfiguredModules(){
this.getModules()
.then(modules => this.configuredModules = modules);
console.log('finished configuredModules');
}
getModules(): Promise<Module[]> {
return this.http.get('http://localhost:8080/rest/modules/configuredModules')
.toPromise()
.then(response => response.json().data as Module[])
;
}
ngOnInit() {
this.getConfiguredModules();
}
buttonClicked(){
console.log('button clicked');
console.log(this.configuredModules.values);
}
}
如果我期待在Chrome中的我的網絡選項卡上,我可以看到下面的未來(下響應):
{"modules":[{"type":"myTestType","physicalLocationName":"myTestPhysicalLocation"}]}
所以我知道數據正在進入,但它不會填滿我的數組。有什麼建議麼? 我覺得我的代碼看起來對角2的英雄教程完全相同: https://angular.io/docs/ts/latest/tutorial/toh-pt6.html
你有沒有嘗試的console.log (JSON.stringify(this.configuredModules)); ? – stwissel
究竟在哪裏是未定義的?在按鈕點擊事件?它應該是'console.log(this.configuredModules);' – micronyks
我把它的數組是未定義的? 我也試圖記錄它的.values,然後我只是得到undefined。如果我在上面的例子中使用.values,它會說:TypeError:無法讀取未定義的屬性'值'。這導致我相信configuredModules是未定義的。我試圖JSON.stringify它,結果相同:undefined –