我想在sqlite中插入后检索我的文章,但是我应该检索它们的变量是null。
这是这篇文章的延续:Function that does not execute
我有一个sqliteservice.ts,它允许您创建数据库和表,然后插入和检索数据。插入数据但我无法在变量中检索它。我在我的页面的构造函数中调用我的函数。
我的服务插入数据并调用函数来检索它们:
public saveAllArticles(article) {
let insertions: Array<Promise<any>> = [];
for (let data in article) {
insertions.push(this.db.executeSql("INSERT INTO `all_articles` (id, titre) VALUES (" +
article[data].article_id + ',"' +
article[data].article_titre + "\")", {}))
Promise.all(insertions).then(() => {
console.log("All records have been inserted");
this.allArticles = this.retrieveAllArticles();
}).catch(e => {
console.log("Erreur :" + JSON.stringify(e))
});
}
}
当我做一个console.log(插入);在循环之前,我的控制台没有结果,在循环中有这样的错误:
未捕获(承诺)TypeError:无法读取未定义的属性'push'
而this.allArticles为null。
检索我的文章的函数,这个函数没有调用因为console.log('Retrieve');未显示:
public retrieveAllArticles() {
console.log("Retrieve");
this.allArticles = [];
this.db.executeSql('SELECT id FROM `all_articles`', {})
.then((data) => {
if(data == null) {
console.log('null');
return;
}
if(data.rows) {
if(data.rows.length > 0) {
for(let i = 0; i < data.rows.length; i++) {
this.allArticles.push(data.rows.item(i).article_id);
}
}
}
return this.allArticles;
});
}
我的页面的构造函数:
allArticles: any;
observable$;
constructor(public navCtrl: NavController,
public modalCtrl: ModalController,
protected articlesService: ArticlesService,
protected sqliteService: SqliteService,
private network: Network,
public toastCtrl: ToastController,
public platform: Platform)
{
this.observable$ = this.articlesService.getAllArticles();
if (this.platform.is('cordova')) {
sqliteService.createDatabaseFile();
this.articlesService.getAllArticles().subscribe(article => {
this.allArticles = article;
this.sqliteService.saveAllArticles(this.allArticles);
});
this.allArticles = this.sqliteService.allArticles;
}
}
saveAllArticles有问题,它可能看起来像这样:
public saveAllArticles(article) {
return Promise.all(//return something so you know when saveAllArticles is done
//assuming article is an array if it's itterable you may try Array.from(article)
article.map(
data=>
this.db.executeSql(
"INSERT INTO `all_articles` (id, titre) VALUES (" +
article[data].article_id + ',"' +
article[data].article_titre + "\")"
,{}
)
)
)
.then(() => {
console.log("All records have been inserted");
this.allArticles = this.retrieveAllArticles();
}).catch(e => {
console.log("Erreur :" + JSON.stringify(e))
});
}
retrieveAllArticles返回undefined,不确定这是否是你想要的。您可能希望该函数返回一些内容。