Hi Guys im completely new to Ionic 2,
But i know js/ts and all that fun stuff already. Now i want to use PouchDb in my ionic app here is my home.ts file:
import { Component } from '#angular/core';
import * as PouchDB from 'pouchdb';
import cordovaSqlitePlugin from 'pouchdb-adapter-cordova-sqlite';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
}
PouchDB.plugin(cordovaSqlitePlugin);
var db = new PouchDB('test', { adapter: 'cordova-sqlite' });
function setData(data) {
var todo = {
title: data,
completed: false
};
db.post(todo, function callback(err, result) {
if (!err) {
console.log('Successfully posted a todo!');
}
});
}
function getData() {
console.log(db.allDocs);
}
Here is my first problem var db = new PouchDb....is no fuction when I put in a on startup function i get an error because my "setData" function doesnt know what "db" is. How can i fix that? And is my importing stuff right?
Next question do i have to import that stuff in my app.module.ts file too? an do i need a provider?
import { NgModule, ErrorHandler } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { AboutPage } from '../pages/about/about';
import { ContactPage } from '../pages/contact/contact';
import { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
#NgModule({
declarations: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AboutPage,
ContactPage,
HomePage,
TabsPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}]
})
export class AppModule {}
I think thats everything for now. Thank you for your help
First, you need to install the SQLite provider.
Here is a tutorial for setting up the PouchDb In Ionic Using SQLite as the database.
https://gonehybrid.com/how-to-use-pouchdb-sqlite-for-local-storage-in-ionic-2/
If you need more help, just comment and I will improve the answer.
Related
(I’m from Germany, so I’m sorry if my English is a little messy…)
Hello,
I am trying to create an Ionic-App, which has a register/login function based on this tutorial:
https://devdactic.com/login-ionic-2/
If I copy the code from the shown app.module.ts exactly like this, I’ll always get the error
“No component factory found for LoginPage. Did you add it to
#NgModule.entryComponents?”
when I try to execute the Code (ionic serve or ionic serve -l).
To fix this error, I added the LoginPage to the declarations and entryComponents in the app.module.ts, so my Code looks like this:
import { AuthServiceProvider } from './../providers/auth-service/auth-service';
import { BrowserModule } from '#angular/platform-browser';
import { ErrorHandler, NgModule } from '#angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '#ionic-native/splash-screen';
import { StatusBar } from '#ionic-native/status-bar';
import { MyApp } from './app.component';
import { LoginPage } from '../pages/login/login';
#NgModule({
declarations: [
MyApp,
LoginPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
LoginPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
AuthServiceProvider
]
})
export class AppModule {}
Now I could open the App, login and visit the “member-area” behind the login and everything seemed to work fine.
But if I try to logout, I get a new error.
“Type LoginPage is part of the declarations of 2 modules: AppModule
and LoginPageModule!”
This message makes sense, because it’s true, that I declared LoginPage twice, so I removed the login.module.ts (because I know that I need the declarations in the app.module.ts apparently).
And this is the confusing point: After I did this, I got another new error, which says
“Component LoginPage is not part of any NgModule or the module has not
been imported to your module”!
Summarized: I may declare “LoginPage” only once – if I do it twice, I’ll get an error. If I remove ONE of them, I’ll get another error, that I declared it nowhere…
And now I am really, really desperate how to solve this problem and how to escape the vicious circle! :-(
If I set the RegisterPage (instead of the LoginPage) as root after logout, this works fine. But if I try to set the RegisterPage as root in the beginning (before login), I’ll get the same issue as at the beginning…
On the internet I found only cases with either the “2 declarations”-error OR the “not part of any”-error, but never both, so I really hope, that someone can help me to solve my problem…
Thank you very much in advance!
Here are some extracts of my Code and error messages:
Screenshot of error no. 1
Screenshot of error no. 2
Screenshot of error no. 3
app.component.ts
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { RegisterPage } from '../pages/register/register';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any = RegisterPage;
constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
}
}
home.ts
import { Component } from '#angular/core';
import { NavController, IonicPage } from 'ionic-angular';
import { AuthServiceProvider } from '../../providers/auth-service/auth-service';
#IonicPage()
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
username = '';
email = '';
constructor(private navCtrl: NavController, private auth: AuthServiceProvider) {
let info = this.auth.getUserInfo();
this.username = info['username'];
this.email = info['email'];
}
public logout() {
this.auth.logout().subscribe(succ => {
this.navCtrl.setRoot('LoginPage');
// (if I replace 'LoginPage' with 'RegisterPage', it'll work)
});
}
}
Seems that you should move LoginPage out from declarations (as it is declared in module) and add LoginPageModule under imports.
import { LoginPageModule } from '../pages/login/login.module';
#NgModule({
declarations: [
MyApp
],
imports: [
LoginPageModule,
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [
StatusBar,
SplashScreen,
{
provide: ErrorHandler,
useClass: IonicErrorHandler
},
AuthServiceProvider
]
})
In my Angular2 app am getting the following error Error: (SystemJS) Unexpected value 'ReleasesService' declared by the module 'AppModule'. Please add a #Pipe/#Directive/#Component annotation.
My AppModule:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { routing } from './app.routes';
import { HttpModule } from '#angular/http';
import { SearchFilter } from '../app/search-filter.pipe';
import { ReleasesService } from '../app/releases/releases.service';
import { AppComponent } from './app.component';
import { HomeComponent } from '../app/home/home.component';
import { ReleasesComponent } from '../app/releases/releases.component';
import { DistroComponent } from '../app/distro/distro.component';
import { ContactComponent } from '../app/contact/contact.component';
#NgModule({
imports: [ BrowserModule, HttpModule, routing ],
declarations: [ AppComponent,
SearchFilter,
HomeComponent,
ReleasesComponent,
ReleasesService,
DistroComponent,
ContactComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
My ReleasesService:
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { IRelease } from './release';
import 'rxjs/add/operator/map';
#Injectable()
export class ReleasesService {
getReleases() {
return IRelease;
}
}
How to fix it? I reinstalled the Quickstarter (the base for my App), and having the same error when try to create the service.
declarations is only for declarable classes: Components Directives and Pipes
You can add ReleasesService to providers array
#NgModule({
imports: [ BrowserModule ],
declarations: [ AppComponent ],
providers: [ ReleasesService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
See also
https://angular.io/guide/ngmodule-faq#what-classes-should-i-add-to-declarations
I had a similar problem, occurring while a project had angular2 as dependency and a project dependency (with the failing component) as well. Seems like angular2 metadata gets attached to the direct angular2 dependency, so the component in the project dependency wasn't declared in the angular2 of the project.
Workaround is to remove angular2 from the dependency (declaring it as devDependency there) and only use one angular2 instance.
Be sure the decorator has the caracter #.
If you don´t type # before the decorator function you will have this error message
#Component({ selector: '...', }) -> Correct
Component({ selector: '...', }) -> ERROR MESAGE: 'add a #Pipe/#Directive/#component'
Learning ionic 2, particularly using Storage.
So, I just created a blank app:
ionic start storagetest blank --v2
Following this the docs:
cordova plugin add cordova-sqlite-storage --save
npm install --save #ionic/storage
Then, my app.module.ts looks like this:
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { IonicStorageModule } from '#ionic/storage';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot()
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
And then went ahead to home.ts:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Storage } from '#ionic/storage';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, storage: Storage) {
storage.ready().then(() => {
storage.set('name', 'Max');
storage.get('name').then((val) => {
console.log('Your name is', val);
})
});
}
}
There is nothing in the javascript log. It appears that get() is never returning the value. However, ready() does work, as I have put a console.log() in it.
What is wrong then?
I am running the app on Chrome, Mac OS.
storage.set is asynchronous and returns a promise.So value may not be set when get().then() is called. Try:
storage.ready().then(() => {
storage.set('name', 'Max').then(()=>
storage.get('name').then((val) => {
console.log('Your name is', val);
});
);
});
You have no error handler in then or catch() method which is probably why nothing is logged.
I saw this question: How to use Electron's <webview> within Angular2 app?
And it got me past my initial error but now I'm seeing
zone.js?1478729974810:355 Unhandled Promise rejection: Template parse errors:
'webview' is not a known element:
1. If 'webview' is an Angular component, then verify that it is part of this module.
2. If 'webview' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '#NgModule.schemas' of this component to suppress this message. ("url" [src]="paper.url | path" [original-size]="false" [show-all]="true"></pdf-viewer-->
[ERROR ->]<webview id="inlinePaper" attr.src="{{paper.url | path}}" disablewebsecurity></webview>
</div"): PaperComponent#45:12 ; Zone: <root> ; Task: Promise.then ; Value: Error: Template parse errors:(…) Error: Template parse errors:
'webview' is not a known element:
1. If 'webview' is an Angular component, then verify that it is part of this module.
2. If 'webview' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '#NgModule.schemas' of this component to suppress this message. ("url" [src]="paper.url | path" [original-size]="false" [show-all]="true"></pdf-viewer-->
[ERROR ->]<webview id="inlinePaper" attr.src="{{paper.url | path}}" disablewebsecurity></webview>
</div"): PaperComponent#45:12
at TemplateParser.parse (http://localhost:5555/node_modules/#angular/compiler/bundles/compiler.umd.js:7711:21)
at RuntimeCompiler._compileTemplate (http://localhost:5555/node_modules/#angular/compiler/bundles/compiler.umd.js:17193:53)
at eval (http://localhost:5555/node_modules/#angular/compiler/bundles/compiler.umd.js:17098:85)
at Set.forEach (native)
at compile (http://localhost:5555/node_modules/#angular/compiler/bundles/compiler.umd.js:17098:49)
at ZoneDelegate.invoke (http://localhost:5555/node_modules/zone.js/dist/zone.js?1478729974810:203:28)
at Zone.run (http://localhost:5555/node_modules/zone.js/dist/zone.js?1478729974810:96:43)
at http://localhost:5555/node_modules/zone.js/dist/zone.js?1478729974810:462:57
at ZoneDelegate.invokeTask (http://localhost:5555/node_modules/zone.js/dist/zone.js?1478729974810:236:37)
at Zone.runTask (http://localhost:5555/node_modules/zone.js/dist/zone.js?1478729974810:136:47)
I added CUSTOM_ELEMENTS_SCHEMA to both my root module and the other module in play here as well as trying the NO_ERRORS_SCHEMA described in the angular documentation for NgModule but I'm still seeing this same template error.
This project has a lot of files and I won't list them all here but feel free to ask for whatever you might feel relevant.
This was built from the angular2 advanced seed at https://github.com/NathanWalker/angular-seed-advanced
My root module 'web.module.ts':
// angular
import { NgModule, NO_ERRORS_SCHEMA } from '#angular/core';
import { APP_BASE_HREF } from '#angular/common';
import { BrowserModule } from '#angular/platform-browser';
import { RouterModule } from '#angular/router';
import { Http } from '#angular/http';
// libs
import { StoreModule } from '#ngrx/store';
import { EffectsModule } from '#ngrx/effects';
import { TranslateLoader } from 'ng2-translate';
// app
import { AppComponent } from './app/components/app.component';
import { ToolbarComponent } from './app/components/toolbar/toolbar.component';
import { HomeComponent } from './app/components/home/home.component';
import { routes } from './app/components/app.routes';
// feature modules
import { CoreModule } from './app/frameworks/core/core.module';
import { AnalyticsModule } from './app/frameworks/analytics/analytics.module';
import { multilingualReducer, MultilingualEffects } from './app/frameworks/i18n/index';
import { MultilingualModule, translateFactory } from './app/frameworks/i18n/multilingual.module';
import { SampleModule } from './app/frameworks/sample/sample.module';
import { EventModule } from './app/components/event/event.module';
// config
import { Config, WindowService, ConsoleService, EventService } from './app/frameworks/core/index';
Config.PLATFORM_TARGET = Config.PLATFORMS.WEB;
if (String('<%= ENV %>') === 'dev') {
// only output console logging in dev mode
Config.DEBUG.LEVEL_4 = true;
}
// sample config (extra)
import { AppConfig } from './app/frameworks/sample/services/app-config';
import { MultilingualService } from './app/frameworks/i18n/services/multilingual.service';
// custom i18n language support
MultilingualService.SUPPORTED_LANGUAGES = AppConfig.SUPPORTED_LANGUAGES;
let routerModule = RouterModule.forRoot(routes);
if (String('<%= TARGET_DESKTOP %>') === 'true') {
Config.PLATFORM_TARGET = Config.PLATFORMS.DESKTOP;
// desktop (electron) must use hash
routerModule = RouterModule.forRoot(routes, {useHash: true});
}
declare var window, console;
// For AoT compilation to work:
export function win() {
return window;
}
export function cons() {
return console;
}
#NgModule({
imports: [
BrowserModule,
CoreModule.forRoot([
{ provide: WindowService, useFactory: (win) },
{ provide: ConsoleService, useFactory: (cons) }
]),
routerModule,
AnalyticsModule,
MultilingualModule.forRoot([{
provide: TranslateLoader,
deps: [Http],
useFactory: (translateFactory)
}]),
StoreModule.provideStore({
i18n: multilingualReducer,
}),
EventModule
],
declarations: [
AppComponent,
HomeComponent,
ToolbarComponent
],
providers: [
{
provide: APP_BASE_HREF,
useValue: '<%= APP_BASE %>'
},
EventService
],
bootstrap: [AppComponent],
schemas: [NO_ERRORS_SCHEMA]
})
export class WebModule { }
Here is my sub module the event module:
// angular
import { NgModule, ModuleWithProviders, Optional, SkipSelf, NO_ERRORS_SCHEMA } from '#angular/core';
import { CommonModule } from '#angular/common';
import { FormsModule } from '#angular/forms';
import { RouterModule } from '#angular/router';
import { HttpModule } from '#angular/http';
import { eventComponent } from './event.component';
import { EventDetailsComponent } from './details/event.details.component';
import { EventNavigationComponent } from './navigation/event.navigation.component';
import { EventAlphanavComponent } from './navigation/event.alphanav.component';
import { EventTrackComponent } from './index-track/event.track.component';
import { EventScheduleComponent } from './index-schedule/event.schedule.component';
import { EventAlphaComponent } from './index-alpha/event.alpha.component';
import { EventAuthorComponent } from './index-author/event.author.component';
import { EventAuthorListComponent } from './index-author/list/event.author.list.component';
import { EventSponsorComponent } from './sponsors/event.sponsor.component';
import { EventExhibitorComponent } from './exhibitors/event.exhibitor.component';
import { EventActivitiesComponent } from './activities/event.activities.component';
import { PaperComponent } from './paper/paper.component';
// libs
import { StoreModule } from '#ngrx/store';
// app
import { Config, WindowService, ConsoleService, EventService, Path } from '../../frameworks/core/index';
// state
/**
* Do not specify providers for modules that might be imported by a lazy loaded module.
*/
#NgModule({
imports: [
CommonModule,
HttpModule,
RouterModule,
StoreModule
],
schemas: [ NO_ERRORS_SCHEMA ],
declarations: [
eventComponent,
EventDetailsComponent,
EventNavigationComponent,
EventAlphanavComponent,
EventTrackComponent,
EventScheduleComponent,
EventAlphaComponent,
EventAuthorComponent,
EventAuthorListComponent,
EventSponsorComponent,
EventExhibitorComponent,
EventActivitiesComponent,
PaperComponent,
Path
]
})
export class EventModule {
constructor(#Optional() #SkipSelf() parentModule: EventModule) {
if (parentModule) {
throw new Error('SampleModule already loaded; Import in root module only.');
}
}
}
Any clue what I'm doing wrong here? Will this even work once I have this template problem worked out?
Any direction at all is appreciated. I'm following what instructions I can find but it's still not working. Thanks in advance!
Create a dummy directive for webview.
import { Directive } from '#angular/core';
#Directive({
selector: 'webview'
})
/** Dummy directive to allow html-tag 'webview' */
export class WebviewDirective {}
and add it to your AppModule declarations array:
...
import { WebviewDirective } from './webview.directive';
#NgModule({
imports: [...],
declarations: [..., WebviewDirective],
providers: [...],
bootstrap: [...]
})
export class AppModule {}
Credits to Philipp for his answer: https://stackoverflow.com/a/39290383/6028371
There must have been some problem with my testing. The above code worked after rebuilding the project and the webview element does what it needs to do in the electron context.
So I am trying to add a new page to my Ionic app.. I have created the folder 'searchpage' via 'ionic generate page searchpage' in the command line. I have then added...
import { Searchpage } from '../searchpage/searchpage';
to the top of 'home.ts' and with this as the #Component underneath...
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, public authData: AuthData) {
}
logMeOut() {
this.authData.logoutUser().then( () => {
this.navCtrl.setRoot(LoginPage);
});
}
searchPage(){
this.nav.push(Searchpage);
}
}
and then in home.html i add the button...
<button ion-button color="positive" block (click)="searchPage()">
Search Page
</button>
the button appears but doesn't do anything on click.
Please help what am i doing wrong?
You also need to import the new page in your app.module.ts file.
Then add it to the declarations and entryComponents arrays. See the example below:
import { NgModule } from '#angular/core';
import { IonicApp, IonicModule } from 'ionic-angular';
import {
Devices,
} from '../providers';
import { MyApp } from './app.component';
import { Login } from '../pages/login/login';
import { Page1 } from '../pages/page1/page1';
import { Page2 } from '../pages/page2/page2';
#NgModule({
declarations: [
MyApp,
Login,
Page1,
Page2,
],
imports: [
IonicModule.forRoot(MyApp),
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
Login,
Page1,
Page2
],
providers: [
Devices,
]
})
export class AppModule { }