#javascript #typescript #ionic2
#javascript #typescript #ionic2
Вопрос:
Я использую Ionic2 для реализации приложения, которое использует SQLite.
Я получаю следующую ошибку, и если кто-нибудь может помочь, я был бы признателен. На самом деле я не уверен, где искать.
EXCEPTION: Error in ./AppRoot class AppRoot_Host - inline template:0:0 app.bundle.js:44905
EXCEPTION: Error in ./AppRoot class AppRoot_Host - inline template:0:0 app.bundle.js:44896
ORIGINAL EXCEPTION: Can't resolve all parameters for ChatsStorageService: (?). app.bundle.js:44896
ORIGINAL STACKTRACE: app.bundle.js:44896
Error: Can't resolve all parameters for ChatsStorageService: (?).
at new BaseException (file:///android_asset/www/build/js/app.bundle.js:25523:24)
at CompileMetadataResolver.getDependenciesMetadata (file:///android_asset/www/build/js/app.bundle.js:38037:20)
at CompileMetadataResolver.getTypeMetadata (file:///android_asset/www/build/js/app.bundle.js:37918:27)
at file:///android_asset/www/build/js/app.bundle.js:38072:31
at Array.map (native)
at Object.Call (file:///android_asset/www/build/js/es6-shim.min.js:10:4652)
at Array.map (file:///android_asset/www/build/js/es6-shim.min.js:10:19780)
at CompileMetadataResolver.getProvidersMetadata (file:///android_asset/www/build/js/app.bundle.js:38060:27)
at CompileMetadataResolver.getDirectiveMetadata (file:///android_asset/www/build/js/app.bundle.js:37868:35)
at RuntimeCompiler._getCompiledHostTemplate (file:///android_asset/www/build/js/app.bundle.js:36412:52)
chatsStorageService.ts
import { Injectable } from "@angular/core";
import { SQLite } from 'ionic-native';
import { Chat, Message } from 'api/models';
import { Messages } from 'api/collections';
import { SqlDatabase } from './SqlDatabase';
import { isBrowser } from './platform';
import { SqlResultSet } from './SqlResultSet';
@Injectable()
export class ChatsStorageService {
private database = null;
private databaseName: string = 'data.db.thewhozoo';
public chats: Array<Chat> = new Array<Chat>();
public messages: Array<Message> = new Array<Message>();
private dbPromise: Promise<SqlDatabase>;
constructor(private _db: any) {
}
public createDatabase(): void {
const createChatsTable: string = "CREATE TABLE IF NOT EXISTS chats (_id TEXT PRIMARY KEY, memberIds TEXT, title TEXT, subTitle TEXT, picture TEXT, lastMessageId TEXT, lastMessageCreatedAt DATE)";
const createMessagesTable: string = "CREATE TABLE IF NOT EXISTS messages (_id TEXT PRIMARY KEY, chatId TEXT, senderId TEXT, ownership TEXT, content TEXT, createdAt DATE, changeDate BOOLEAN, readByReceiver BOOLEAN)";
this.dbPromise = SqlDatabase.open(this.databaseName, [createChatsTable, createMessagesTable]);
this.dbPromise.then((data) => {
console.log('database ' this.databaseName ' created');
});
}
public refreshChats(): Promise<any> {
const statement: string = "SELECT * FROM chats";
return this.dbPromise
.then((db) => db.execute(statement))
.then((resultSet) => {
this.chats = [];
if (resultSet.rows.length > 0) {
for (var i = 0; i < resultSet.rows.length; i ) {
this.populateChat(resultSet.rows.item(i));
}
}
});
}
private populateChat(chatItem: any): Promise<any> {
const statement: string = "SELECT * FROM messages where _id = ?";
const params: string[] = [chatItem.lastMessageId];
let messages: Array<Message> = new Array<Message>();
return this.dbPromise
.then((db) => db.execute(statement, params))
.then((messageData) => {
this.chats = [];
if (messageData.rows.length > 0) {
for (var j = 0; j < messageData.rows.length; j ) {
if (messageData.rows.item(j)) {
let messageValue: Message = { _id: messageData.rows.item(j)._id, chatId: messageData.rows.item(j).chatId, senderId: messageData.rows.item(j).senderId, ownership: messageData.rows.item(j).ownership, content: messageData.rows.item(j).content, createdAt: messageData.rows.item(j).createdAt, changeDate: messageData.rows.item(j).changeDate, readByReceiver: messageData.rows.item(j).readByReceiver };
messages.push(messageValue);
}
}
}
let chatValue: Chat = {
_id: chatItem._id, memberIds: chatItem.memberIds, title: chatItem.title, subTitle: chatItem.subTitle,
picture: chatItem.picture, lastMessage: messages[0], lastMessageCreatedAt: chatItem.lastMessageCreatedAt
};
if (this.chats.indexOf(chatValue) === -1) {
this.chats.push(chatValue);
}
});
}
public refreshMessages(): Promise<any> {
const statement: string = "SELECT * FROM messages";
return this.dbPromise
.then((db) => db.execute(statement))
.then((resultSet) => {
this.messages = [];
if (resultSet.rows.length > 0) {
for (var i = 0; i < resultSet.rows.length; i ) {
if (resultSet.rows.item(i)) {
this.messages.push({ _id: resultSet.rows.item(i)._id, chatId: resultSet.rows.item(i).chatId, senderId: resultSet.rows.item(i).senderId, ownership: resultSet.rows.item(i).ownership, content: resultSet.rows.item(i).content, createdAt: resultSet.rows.item(i).createdAt, changeDate: resultSet.rows.item(i).changeDate, readByReceiver: resultSet.rows.item(i).readByReceiver });
}
}
}
});
}
public addChat(chat: Chat): Promise<any> {
if (window.cordova) {
if (this.chats.indexOf(chat) < 0) {
const statement: string = "INSERT INTO chats (_id, memberIds, title, subTitle, picture, lastMessageId, lastMessageCreatedAt) VALUES (?, ?, ?, ?, ?, ?, ?)";
const params: any[] = [chat._id, chat.memberIds, chat.title, chat.subTitle, chat.picture, chat.lastMessage._id, chat.lastMessageCreatedAt];
this.chats.push(chat);
return this.dbPromise
.then((db) => db.execute(statement, params))
.then((resultSet) => {
console.log('added chat: ', resultSet);
});
}
}
}
public updateChat(chat: Chat): Promise<any> {
if (window.cordova) {
let idx: number = this.contains(this.chats, chat);
if (idx >= 0) {
this.chats[idx] = chat;
const statement: string = "UPDATE chats SET memberIds = ?, title = ?, subTitle = ?, picture = ?, lastMessageId = ?, lastMessageCreatedAt = ? WHERE _id = ?"
const params: any[] = [chat.memberIds, chat.title, chat.subTitle, chat.picture, chat.lastMessage._id, chat.lastMessageCreatedAt, chat._id];
return this.dbPromise
.then((db) => db.execute(statement, params))
.then((resultSet) => {
console.log('updated chat: ', resultSet);
});
}
}
}
public updateMessage(message: Message): Promise<any> {
if (window.cordova) {
let idx: number = this.contains(this.messages, message);
if (idx >= 0) {
this.messages[idx] = message;
const statement: string = "UPDATE messages SET readByReceiver = ? WHERE _id = ?";
const params: any[] = [message.readByReceiver, message._id];
return this.dbPromise
.then((db) => db.execute(statement, params))
.then((resultSet) => {
console.log('updated message: ', resultSet);
});
}
}
}
private contains(arr: Array<any>, obje: any): number {
for (let i: number = 0; i < arr.length; i ) {
if (arr[i]._id === obje._id) {
return i;
}
}
return -1;
}
public removeChat(chat: Chat): Promise<any> {
if (window.cordova) {
let idx: number = this.chats.indexOf(chat);
if (idx >= 0) {
const selectStatement: string = "SELECT * FROM chats where _id = ?";
const selectParams: string[] = [chat._id];
const deleteStatement: string = "DELETE FROM chats where _id = ?";
const deleteParams: string[] = [chat._id];
for (let i: number = 0; i < this.messages.length; i ) {
if (this.messages[i].chatId === chat._id) {
this.removeMessage(this.messages[i]);
}
}
this.chats.splice(idx, 1);
return this.dbPromise
.then((db) => db.execute(selectStatement, selectParams))
.then((resultSet) => {
if (resultSet amp;amp; resultSet.rows.length > 0) {
return this.dbPromise
.then((db) => db.execute(deleteStatement, deleteParams))
.then((resultSet) => {
console.log('chat deleted: ', resultSet);
});
}
});
}
}
}
public addMessage(chat: Chat, message: Message): Promise<Message> {
let promise: Promise<Message> = new Promise<Message>(resolve => {
if (window.cordova) {
const statement: string = "SELECT * FROM chats where _id = ?";
const params: string[] = [chat._id];
return this.dbPromise
.then((db) => db.execute(statement, params))
.then((resultSet) => {
if (!resultSet || resultSet.rows.length === 0) {
this.addChat(chat);
}
if (this.messages.indexOf(message) < 0) {
this.addTheMessage(message);
}
});
}
});
return promise;
}
private addTheMessage(message: Message): Promise<any> {
const selectStatement: string = "SELECT * FROM messages where _id = ?";
const selectParams: string[] = [message._id];
const insertStatement: string = "INSERT INTO messages (_id, chatId, senderId, ownership, content, createdAt, changeDate, readByReceiver) VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
const insterParams: any[] = [message._id, message.chatId, message.senderId, message.ownership, message.content, message.createdAt, message.changeDate, message.readByReceiver];
return this.dbPromise
.then((db) => db.execute(selectStatement, selectParams))
.then((resultSet) => {
if (!resultSet || resultSet.rows.length === 0) {
return this.dbPromise
.then((db) => db.execute(insertStatement, insterParams))
.then((resultSet) => {
if (!resultSet || resultSet.rows.length === 0) {
let length: number = this.messages.push(message);
console.log('message inserted: ' length, message);
}
});
}
});
}
public removeMessage(message: Message): Promise<any> {
if (window.cordova) {
let idx: number = this.messages.indexOf(message);
if (idx >= 0) {
const selectStatement: string = "SELECT * FROM messages where _id = ?";
const selectParams: string[] = [message._id];
const deleteStatement: string = "DELETE FROM messages where _id = ?";
const deleteParams: string[] = [message._id];
this.messages.splice(idx, 1);
return this.dbPromise
.then((db) => db.execute(selectStatement, selectParams))
.then((resultSet) => {
if (resultSet amp;amp; resultSet.rows.length > 0) {
return this.dbPromise
.then((db) => db.execute(deleteStatement, deleteParams))
.then((resultSet) => {
console.log('message deleted: ', message);
});
}
});
}
}
}
public findLastMessageForChat(chat: Chat): Promise<Message> {
let promise: Promise<Message> = new Promise<Message>(resolve => {
const statement: string = "SELECT * FROM messages where chatId = ? order by createdAt desc";
const params: string[] = [chat._id];
return this.dbPromise
.then((db) => db.execute(statement, params))
.then((data) => {
let message: Message = null;
if (data.rows.length > 0) {
for (var i = 0; i < data.rows.length; i ) {
if (data.rows.item(i)) {
message = ({ _id: data.rows.item(i)._id, chatId: data.rows.item(i).chatId, senderId: data.rows.item(i).senderId, ownership: data.rows.item(i).ownership, content: data.rows.item(i).content, createdAt: data.rows.item(i).createdAt, changeDate: data.rows.item(i).changeDate, readByReceiver: data.rows.item(i).readByReceiver });
break;
}
}
}
resolve(message);
});
});
return promise;
}
}
SQLDatabase.ts
import { isBrowser } from './platform';
import { SqlResultSet } from './SqlResultSet';
export class SqlDatabase {
constructor(private _db: any) { }
static open(name: string, initStatements: string[] = []): Promise<SqlDatabase> {
let dbPromise = isBrowser()
.then(browser => {
const openDatabase = browser ? openBrowserDatabase : openCordovaDatabase;
return openDatabase(name);
});
if (initStatements.length === 0) {
return dbPromise;
}
let _db: SqlDatabase;
// execute the first statement and capture the _db
dbPromise.then(db => {
_db = db;
return db.execute(initStatements.shift());
});
// execute all the other statements (if any) sequentially
for (let sql of initStatements) {
dbPromise.then(() => {
_db.execute(sql)
});
}
// resolve the _db only after all statements have completed
return new Promise((resolve, reject) => {
dbPromise.then(() => resolve(_db)).catch(reject);
});
}
execute(statement: string, params: any[] = []): Promise<SqlResultSet> {
return new Promise((resolve, reject) => {
this._db.transaction(tx => tx.executeSql(statement, params, (tx, resultSet) => {
resolve(resultSet);
}, (tx, error) => {
reject(error)
}));
});
}
}
declare var sqlitePlugin: any;
function openCordovaDatabase(name: string): Promise<SqlDatabase> {
return new Promise((resolve, reject) => {
if (typeof sqlitePlugin === 'undefined') {
reject(new Error('[ionix-sqlite] sqlitePlugin global object not found; did you install a Cordova SQLite plugin?'));
}
const db = sqlitePlugin.openDatabase({
name: name,
location: 'default'
});
console.info('[ionix-sqlite] using Cordova sqlitePlugin');
resolve(new SqlDatabase(db));
});
}
declare function openDatabase(name: string, version: string, desc: string, size: number): any;
function openBrowserDatabase(name: string): Promise<SqlDatabase> {
return new Promise((resolve, reject) => {
try {
const db = openDatabase(name, '1.0', name, -1);
console.info('[ionix-sqlite] using WebSQL');
resolve(new SqlDatabase(db));
} catch (error) {
reject(error);
}
});
}
platform.ts
declare var cordova;
export function isBrowser(): Promise<boolean> {
if (typeof cordova === 'undefined') {
return Promise.resolve(true);
}
return new Promise(resolve => {
document.addEventListener('deviceready', () => {
resolve(cordova.platformId === 'browser');
});
});
}
SqlResultSet.ts
import { SqlResultSetRows } from './SqlResultSetRows';
export interface SqlResultSet {
insertId: number;
rowsAffected: number;
rows: SqlResultSetRows;
}
SqlResultSetRows.ts
export interface SqlResultSetRows {
length: number;
item(index: number): any;
}
Ответ №1:
Проблема заключалась в том, что у меня было что-то в конструкторе chatsStorageService
.ts, что нужно было удалить.
constructor(private _db: any) { }
Для
constructor() { }