【发布时间】:2017-12-19 18:27:14
【问题描述】:
我想在我插入到 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(insertions);在循环之前,我的控制台中没有结果,在循环中有这个错误:
Uncaught (in promise) TypeError: Cannot read property 'push' of undefined
而 this.allArticles 为空。
检索我的文章的函数,这个函数没有被调用,因为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;
}
}
【问题讨论】:
-
没人帮我吗? :(
-
你在哪里调用retrieveAllArticles?
this.allArticles = this.sqliteService.allArticles;是什么? -
我在 saveAllArticles() 中调用了 retrieveAllArticles()。不,是 this.allArticles = this.retrieveAllArticles();
-
能否请您在问题中设置正确的代码?你的构造函数中还有
this.allArticles = this.sqliteService.allArticles;.. -
因为我想将我的函数的结果存储在我的服务的变量 allArticles 中,并设置我的页面的变量 allArticles(它是同名,但不是同一个变量,这可能会造成混淆)
标签: javascript angular sqlite typescript ionic-framework