在我的情况下,我必须获取customerService上的客户列表并返回组件。请任何人都可以通过重写getCustomersList方法来帮助我。
import { Injectable } from '@angular/core';
import { SQLite } from 'ionic-native';
@Injectable()
export class CustomerService {
private sDBName:string;
private db;
private isDBExist:boolean = false;
constructor() {}
setDBName(sDBName:string) {
this.sDBName = sDBName;
}
connect():Promise<any> {
this.db = new SQLite();
return this.db.openDatabase({
name: this.sDBName,
location: 'default'
});
}
getCustomersList():Promise<any> {
return Promise.resolve(()=>{
return this.connect().then(()=>{
this.isDBExist = true;
let sql = 'SELECT * FROM customer ORDER BY customer_id DESC LIMIT 10';
return this.db.executeSql(sql, {}).then((result)=>{
let customers = [];
for(let i=0; i<result.rows.length; i++) {
customers.push(result.rows.item(i));
}
return customers;
},(err)=>{
this.debug('Unable to select customers', err);
return [];
});
},(err)=>{
this.debug('Unable to open database', err);
return [];
});
});
}
}
答案 0 :(得分:3)
你以绝对不自然的方式使用Promise。创造了Promise以摆脱所谓的回调地狱。 Promise应该会降低异步代码的复杂性,但你所做的正是通往回调地狱的道路。
我稍微改写了你的功能,以便按照Promise标准工作。它可能不是一个开箱即用的解决方案,但你没有向我们提供任何plunker,所以这只是一个概念:
getCustomersList(): Promise<any> {
return this.connect()
.catch(err => throw new Error('Unable to open database', err))
.then(() => {
this.isDBExist = true;
return this.db.executeSql('SELECT * FROM customer ORDER BY customer_id DESC LIMIT 10', {})
})
.catch('cannot execute query')
.then(result => result.rows.map(row => row.item(i)))
.catch(err => {
this.debug('Unable to select customers', err);
return [];
});
}
我真的相信不应该在这个地方连接到数据库,而是在一些常见的数据库服务上,这将是你的数据库层。理想情况下,当您调用此函数时,数据库应该已经连接/应该已经抛出错误。所以花更多的时间来考虑架构。
答案 1 :(得分:1)
您的方法getCustomersList
应该返回客户列表,还是查询客户列表的函数?如果它是前者,那就是要走的路:
getCustomersList(): Promise<any> {
return this.connect().then(() => {
this.isDBExist = true;
let sql = 'SELECT * FROM customer ORDER BY customer_id DESC LIMIT 10';
return this.db.executeSql(sql, {}).then((result) => {
let customers = [];
for (let i = 0; i < result.rows.length; i++) {
customers.push(result.rows.item(i));
}
return customers;
}, (err) => {
this.debug('Unable to select customers', err);
return [];
});
}, (err) => {
this.debug('Unable to open database', err);
return [];
})
}