[英]ionic3 how can i inject service/provider inside ErrorHandlerService
[英]SqlStorage Ionic 2 as a service/provider
我有一個離子二的提供者,我有這個:
getCategory() {
this.storage.query('SELECT * FROM category')
.then((data) => {
var category = [];
if (data.res.rows.length > 0) {
for (var i = 0; i < data.res.rows.length; i++) {
category.push({
name: data.res.rows.item(i).name,
type: data.res.rows.item(i).type,
note: data.res.rows.item(i).note
});
}
}
// console.log(JSON.stringify(category));
return category; // is this correct?
}, (error) => {
console.log('Error -> ' + JSON.stringify(error.err));
});
}
然后我希望在注入服務后在我的頁面中做這樣的事情:
constructor(nav, theservice) {
this.nav = nav;
this.service = theservice
this.category = service.getCategory()
}
我如何返回結果以便能夠使用? 當我控制台記錄this.category
時,嘗試上述操作沒有任何this.category
關於如何在 ionic 2 中使用 sqlite的教程很有幫助,但無法弄清楚如何將它們轉換為服務/提供程序。
更新(2016 年 6 月 15 日)
我在下面的原始答案中分享了一個鏈接。 線程上發生了更多討論,較早的回答方法雖然有效,但可能不是最佳實踐。 在這里更新:
service.js
// using beta 7 ionic 2
import {Injectable} from '@angular/core';
import { Storage, SqlStorage } from 'ionic-angular';
@Injectable()
export class CategoryService {
static get parameters(){
return []
}
constructor() {
this.storage = new Storage(SqlStorage);
this.storage.query('CREATE TABLE IF NOT EXISTS category (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, type TEXT)');
}
getCategory() {
return this.storage.query('SELECT id, name, type FROM category');
}
}
然后上面的服務是這樣使用的:
somewhereInCategoryPage.js
文件
loadCategory() {
this.platform.ready().then(() => {
this.service.getCategory()
.then(data => {
this.category = [];
if (data.res.rows.length > 0) {
for (var i = 0; i < data.res.rows.length; i++) {
let item = data.res.rows.item(i);
this.category.push({
'id': item.id,
'name': item.name,
'type': item.type
});
}
}
console.log(this.category);
}, error => {
console.log('Error', error.err)
})
});
}
剛剛想到更新,可能對誰知道有用。
舊答案離開這里以供參考
我最終決定的是什么。 在這里發帖,可能會幫助某人。 離子論壇上此線程的指導
在服務/提供者中
getCategory() {
var storage = new Storage(SqlStorage);
return new Promise(function(resolve, reject) {
return storage.query('SELECT name, type, note FROM category')
.then((data) => {
// kinda lazy workaround
resolve(data.res.rows);
});
});
}
在構造函數中:
static get parameters() {
return [ [Myservice] ];
}
constructor(myservice) {
myservice.getCategory()
.then((category) => {
// recreate new array from old category array, or else:
// EXCEPTION: Cannot find a differ supporting object
// https://github.com/angular/angular/issues/6392#issuecomment-171428006
this.categories = Array.from(category);
console.log(this.categories);
})
.catch((error) => {
console.log(error);
});
}
在模板中:
<ion-list>
<button ion-item *ngFor="#category of categories">
{{ category.name }}
<br>
<ion-icon name="arrow-forward" item-right></ion-icon>
</button>
</ion-list>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.