我正在使用类似的角度服务进行二元yo保存数据:
@Injectable()
export class DataServiceProvider {
url;
jsonArr = [];
constructor(public http: Http) {
this.url='assets/data/userProfiles.json';
}
getProfiles(){
return new Promise(resolve => {
this.http.get(this.url).
subscribe(data => {
resolve(data.json());
}, err => {
console.log(err);
});
});
}
proccessProfiles(){
this.getProfiles().then(
data=>{
data[0].companies.forEach(function(cur){
this.jsonArr.push({
name: cur.name,
profile: "company"
});
})
data[1].centers.forEach(function(cur){
this.jsonArr.push({
name: cur.name,
profile: "center"
});
})
}
)
}
}
当我在我的app.component.ts中打电话:
我已经导入了:
从'../提供者/data-service/data-service'import {dataServiceProvider};
,在此功能中,我称为
openPopup(){
console.log('Openpopup ');
this.modalCtrl.create(ProfilePage).present();
this._ds.proccessProfiles();
}
它返回错误:
无法读取未定义的
的属性jsonarr您是否可以解决这个问题?
谢谢
您不会在任何地方实例化该服务。如果需要单身人士,则需要将其作为参数之一添加到constructor()
中,并在此注入并检索实例。然后,您可以使用this
访问它。
constuctor(_ds: DataServiceProvider)
尝试通过绑定this
proccessProfiles(){
this.getProfiles().then(
data=>{
data[0].companies.forEach(function(cur){
this.jsonArr.push({
name: cur.name,
profile: "company"
});
}.bind(this)) // changed here
data[1].centers.forEach(function(cur){
this.jsonArr.push({
name: cur.name,
profile: "center"
});
}.bind(this)) //changed here
}
)
}