I would like retrieve my articles after my insert in sqlite, but my variable that is supposed to retrieve them is null.
It's the continuation of this post : Function that does not execute
I have a sqliteservice.ts which allows you to create the database and tables, then insert and retrieve the data. The data is inserted but I can not retrieve it in a variable. I call my functions in the constructor of my page.
My service that inserts the data and calls the function to retrieve them :
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))
});
}
}
When I do a console.log(insertions); before the loop, there is not result in my console, in the loop there is this error :
Uncaught (in promise) TypeError: Cannot read property 'push' of undefined
And this.allArticles is null.
The function to retrieve my articles, this function is not called because the console.log('Retrieve'); is not displayed :
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;
});
}
The constructor of my page :
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;
}
}