Ionic 2 Angular 2获取REST JSON数据
我可能只是在某个地方犯了个愚蠢的错误,但我再也看不到了 我有一个非常简单的Ionic 2 Angular 2应用程序。请不要打扰架构,我只是想先让它工作。我试图用从RESTJSON服务获得的模块对象填充我的数组“configuredModules”。我创建了一个按钮,将数组记录到控制台,这样我可以看到数组的值是什么,但总是未定义的。我做错了什么Ionic 2 Angular 2获取REST JSON数据,angular,ionic-framework,ionic2,Angular,Ionic Framework,Ionic2,我可能只是在某个地方犯了个愚蠢的错误,但我再也看不到了 我有一个非常简单的Ionic 2 Angular 2应用程序。请不要打扰架构,我只是想先让它工作。我试图用从RESTJSON服务获得的模块对象填充我的数组“configuredModules”。我创建了一个按钮,将数组记录到控制台,这样我可以看到数组的值是什么,但总是未定义的。我做错了什么 export class Module { type: string; physicalLocationName: string; }
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);
}
}
所以我知道数据即将到来,但它并没有填满我的数组。有什么建议吗?
我认为我的代码与Angular 2的英雄教程看起来是一样的:
您的错误在此函数中:
getModules(): Promise<Module[]> {
return this.http.get('http://localhost:8080/rest/modules/configuredModules')
.toPromise()
.then(response => response.json().data as Module[]);
}
然后,在单击按钮的函数上,删除值
,如下所示:
getModules(): Promise<Module[]> {
return this.http.get('http://localhost:8080/rest/modules/configuredModules')
.toPromise()
.then(response => response.json().modules as Module[]);
}
buttonClicked(){
console.log('button clicked');
console.log(this.configuredModules);
}
您是否尝试过console.log(JSON.stringify(this.configuredModules))?确切地说,它是未定义的?在按钮点击事件中?它应该是
console.log(this.configuredModules)代码>我认为数组是未定义的?我还尝试在没有.values的情况下记录它,然后我就没有定义。如果我像上面的例子一样使用.values,它会说:TypeError:无法读取未定义的属性“values”。这让我相信configuredModules是未定义的。我试图将其JSON.stringify,结果相同:UnfinedWhat是.values
?好吧,没有什么比.values
更好的了。只需像我在上面的评论中提到的那样使用,我的IDE(Atom)将其作为一个选项。我想它会打印数组中的值。或者至少是什么。没有.values的打印给了我“未定义”的含义,就是这样!非常感谢你,法比奥!你知道为什么Angular 2(英雄教程)的教程设置不同吗?因为他们的API和你的不同。您的API返回一个带有{“modules”:[{“type”:“myTestType”,“physicalLocationName”:“myTestPhysicalLocation”}]}
的对象键,但API良好的实践告诉我们,我们应该始终将API响应封装在数据对象中,请看一看,非常感谢您!你是冠军!
buttonClicked(){
console.log('button clicked');
console.log(this.configuredModules);
}