我有一个带有提供程序的Ionic应用程序,可以保存到sqlite数据库。我想从该提供程序获取返回值,并在我的home
组件中提醒它。如果我在提供程序本身中执行警报,则会成功保存数据或错误。但是如果我尝试将它传递给home
组件,我就不会得到返回的值。请参阅下面的代码。
的DataService
saveData(data:any): Observable<string> {
var statusMessage;
var saveDataScript = 'INSERT INTO lcs VALUES(NULL, ?, ?, ?, ?, ?, ?)';
this.sqlite.create({
name: 'lcs.db',
location: 'default'
}).then((db: SQLiteObject) => {
db.executeSql(saveDataScript, [data.entry_plaza, data.exit_plaza,
data.vehicle_class, data.user_badge, data.scan_time, data.toll_fee])
.then(res => {
statusMessage = 'Data saved.';
})
.catch(e => {
statusMessage = 'Error in saving: ' +e;
})
})
.catch(e => {
statusMessage = 'Error in checking database: ' +e;
})
return statusMessage;
}
home.ts
saveTicket(obj: any) {
var preparedData: any = {
entry_plaza: obj.entryplaza,
exit_plaza: obj.exitplaza,
vehicle_class: this.tellerClass,
user_badge: this.userInfo.badge,
scan_time: new Date().toLocaleString(),
toll_fee: obj.toll,
}
this.dataService.saveData(preparedData).subscribe((reply) => {
this.presentDataAlert(reply);
});
}
在您的帮助下,我能够提出这个有效的代码:
saveData(data: any): Promise<string> {
return new Promise((resolve, reject) => {
var statusMessage;
var saveDataScript = 'INSERT INTO lcs VALUES(NULL, ?, ?, ?, ?, ?, ?)';
this.sqlite.create({
name: 'lcs.db',
location: 'default'
}).then((db: SQLiteObject) => {
db.executeSql(saveDataScript, [data.entry_plaza, data.exit_plaza,
data.vehicle_class, data.user_badge, data.scan_time, data.toll_fee])
.then(res => {
statusMessage = 'Data saved.';
resolve(statusMessage);
}).catch(e => {
statusMessage = 'Error in saving: ' + e;
resolve(statusMessage);
});
}).catch(e => {
statusMessage = 'Error in checking database: ' + e;
resolve(statusMessage);
});
});
}
答案 0 :(得分:1)
saveData(data: any): Observable<string> {
var statusMessage;
var saveDataScript = 'INSERT INTO lcs VALUES(NULL, ?, ?, ?, ?, ?, ?)';
const promise = new Promise((resolve, reject) => {
this.sqlite
.create({
name: 'lcs.db',
location: 'default'
})
.then((db: SQLiteObject) => {
db.executeSql(saveDataScript, [data.entry_plaza, data.exit_plaza,
data.vehicle_class, data.user_badge, data.scan_time, data.toll_fee])
.then(res => {
resolve('Data saved.')
})
.catch(e => {
reject('Error in saving: ' + e)
})
})
.catch(e => {
reject('Error in checking database: ' + e)
})
})
return Observable.fromPromise(promise);
}