Import class into ionic 3 and error when instantiating class - ionic-framework

I'm new to ionic 3 and I'm trying to register. I have a accounts screen called accounts.ts that gets in src/pages/accounts/accounts.ts and then I'm trying to create a class where DAO will be referring to that class, I created it in the following src/dao/dao-accounts.ts location.
Some errors are showing up
My first doubt is this, do you mind this current?
import {DAOContas} from '../../dao/da-contacts';
I am also wanting to return a list of data but an error appears like this
:
uncaught (im promisse): referrererror: value is not defined
referenceerror: value is not defined at new ContasPage
class dao-accounts.ts
export class DAOContas {
constructor()
{
this.list = [];
}
getList()
{
this.list = [
{descricao:"Alimentação"},
{descricao:"Lazer"},
{descricao:"Transporte"}
];
return this.list;
}
}
method ContasPage.ts
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { DAOContas } from '../../dao/dao-contas';
#Component({
selector: 'page-list',
templateUrl: 'contas.html'
})
export class ContasPage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
this.dao = new DAOContas();
this.listcontas = this.dao.getList();
}
}
Error Occurs When Instantiating DAOContas

So the issue here relates to dependency injection pattern. See official documentation of how that works for more info.
Based on the code you provided it seems like the issue is with the way you organized your code and declared (or did not declare) certain variables.
In your ContasPage do ensure you:
import the class
declare the vars
do assignments in the constructor
So in your case you didn't declare the vars before the constructor:
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { DAOContas } from '../../dao/dao-contas';
#Component({
selector: 'page-list',
templateUrl: 'contas.html'
})
export class ContasPage {
// declare your vars here:
dao: any;
listcontas: any;
constructor(
public navCtrl: NavController
) {
this.dao = new DAOContas();
this.listcontas = this.dao.getList();
}
}
Same thing in your class you forgot to declare the var list:
export class DAOContas {
list: Array<{ descricao: string }>
constructor() {
this.list = [];
}
getList() {
this.list = [
{ descricao: "Alimentação" },
{ descricao: "Lazer" },
{ descricao: "Transporte" }
];
return this.list;
}
}
Also since your DAOContas to me looks like a data provider, I would probably think about turning it into a provider and injecting it into your page via constructor:
Make sure DAOContas is injectable:
import { Injectable } from '#angular/core'
#Injectable()
export class DAOContas {
list: Array<{ descricao: string }>
constructor() {
this.list = [];
}
getList() {
this.list = [
{ descricao: "Alimentação" },
{ descricao: "Lazer" },
{ descricao: "Transporte" }
];
return this.list;
}
}
Add it to your app.module.ts as provider:
import { DAOContas } from '../../src/providers/dao-contacts';
#NgModule({
declarations: [
bla
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp
],
providers: [
DAOContas,
StatusBar,
SplashScreen,
{ provide: ErrorHandler, useClass: IonicErrorHandler },
TestProvider
]
})
export class AppModule { }
Finally inject it to your page:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { DAOContas } from '../../providers/dao-contacts';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage2 {
listcontas: any;
constructor(
public navCtrl: NavController,
public dao: DAOContas
) {
this.listcontas = this.dao.getList();
console.log(this.listcontas)
}
}

Related

Error: Can't resolve all parameters for Storage: (?, ?). ionic

I have had this error "NullInjectorError: No provider for Storage!" and then I add Storage in app.module.ts
then I had another error : Error: Can't resolve all parameters for Storage: (?, ?)
and sometime i had this error :
Uncaught TypeError: Cannot read property 'id' of undefined
core.js:24134 Uncaught TypeError: Cannot read property 'id' of undefined
at registerNgModuleType (core.js:24134)
at core.js:24145
at Array.forEach (<anonymous>)
at registerNgModuleType (core.js:24145)
at new NgModuleFactory$1 (core.js:24242)
at compileNgModuleFactory__POST_R3__ (core.js:27786)
at PlatformRef.bootstrapModule (core.js:28024)
at Module../src/main.ts (main.ts:11)
at __webpack_require__ (bootstrap:84)
at Object.0 (main.ts:12
I tried importing IonicStorageModule and it is the same
app.moudle.page.ts file :
import { Component, OnInit } from '#angular/core';
import { NavController, NavParams, LoadingController, AlertController, ModalController } from '#ionic/angular';
import { PersonalinfoService } from 'src/app/services/personalinfo.service';
import { AlertService } from 'src/app/services/alert.service';
import { Saudi } from '../../../app/models/saudi';
import { ErrorsService } from '../../../app/services/errors.service';
#Component({
selector: 'app-personalinfo',
templateUrl: './personalinfo.page.html',
styleUrls: ['./personalinfo.page.scss'],
})
export class PersonalinfoPage{
public personal_info : any;
private loading : any;
constructor(public navCtrl: NavController,
public navParams: NavParams,
private personalinfoService : PersonalinfoService,
private errorsService : ErrorsService,
public modalCtrl: ModalController,
private loadingCtrl : LoadingController,
private alertCtrl : AlertController,
public storage: Storage,
) {
this.personal_info = this.navParams.get('personal_info') || new Saudi();
// هذذا حلو بس ماضبط
// this.loading = this.loadingCtrl.create({
// content: 'Please wait...',
// spinner: 'bubbles'
// });
}
ionViewDidLoad() {
console.log('ionViewDidLoad addInfoPage');
}
addInfo() {
let data = {
personal_info: this.personal_info
}
this.personalinfoService.store( JSON.stringify( data ) ).subscribe(
personal_info => {
this.personal_info = personal_info;
this.loading.dismiss();
this.dismiss( true );
},
);
}
closeModal(){
this.dismiss(false);
}
dismiss( returnParam : boolean ) {
let data = { 'personal_info': this.personal_info, 'returnParam': returnParam };
this.modalCtrl.dismiss( data );
}
}
Register.page.ts file
import { Component, OnInit } from '#angular/core';
import { ModalController, NavController } from '#ionic/angular';
import { LoginPage } from '../login/login.page';
import { AuthService } from 'src/app/services/auth.service';
import { NgForm } from '#angular/forms';
import { AlertService } from 'src/app/services/alert.service';
#Component({
selector: 'app-register',
templateUrl: './register.page.html',
styleUrls: ['./register.page.scss'],
})
export class RegisterPage implements OnInit {
constructor(private modalController: ModalController,
private authService: AuthService,
private navCtrl: NavController,
private alertService: AlertService
) { }
ngOnInit() {
}
dismissRegister() {
this.modalController.dismiss();
}
async loginModal() {
this.dismissRegister();
const loginModal = await this.modalController.create({
component: LoginPage,
});
return await loginModal.present();
}
register(form: NgForm) {
this.authService.register(form.value.name, form.value.email, form.value.password).subscribe(
data => {
this.authService.login(form.value.email, form.value.password).subscribe(
data => {
},
error => {
console.log(error);
},
() => {
this.dismissRegister();
this.navCtrl.navigateRoot('/personalinfo');
}
);
this.alertService.presentToast(data['message']);
},
error => {
console.log(error);
},
() => {
}
);
}
}
before i add personal page everythings works fine.
I have nothing else but there is an id added in the model
update :
I get steps back when it is working and starting again
the thing is it happand again
I have page called Home, Personalinfo
Home is called after success login and called personalinfo page in Home page
I have importing it like this: because I have got this error "No provider for PersonalinfoService!"
home-routing.module.ts
import { NgModule } from '#angular/core';
import { Routes, RouterModule } from '#angular/router';
import { HomePage } from './home.page';
import { PersonalinfoPage } from './../personalinfo/personalinfo.page';
const routes: Routes = [
{
path: '',
component: HomePage
}
];
#NgModule({
imports: [RouterModule.forChild(routes),
PersonalinfoPage
],
exports: [RouterModule],
})
export class HomePageRoutingModule {}
I DID MISS THE
#Injectable({
providedIn: 'root'
})
IN THE SERVICE FILE THATS WHERE CAME ALL THE MISS
THANK YOU
Like it's mentioned in the docs, you need to import IonicStorageModule.forRoot() in the AppModule:
import { IonicStorageModule } from '#ionic/storage';
#NgModule({
declarations: [
// ...
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot() // <--- here!
],
bootstrap: [IonicApp],
entryComponents: [
// ...
],
providers: [
// ...
]
})
export class AppModule {}
Besides that, in your personalifo.ts file, you're injecting Storage but that's not actually Ionic's storage but the Web Storage API – you can see that when hovering on the Storage class:
In order to inject the right dependency, you'd need to add the following import at the top of the file: import { Storage } from '#ionic/storage'; to make sure you're using Ionic's storage:
import { Storage } from '#ionic/storage'; // <--- here!
// ...
#Component({
selector: 'app-personalinfo',
templateUrl: './personalinfo.page.html',
styleUrls: ['./personalinfo.page.scss'],
})
export class PersonalinfoPage {
constructor(
public storage: Storage,
// ...
) {}
}

Nativescript-angular2 Uncaught (in promise): Error: Cannot match any routes with multiple nested routing

I'm developing a mobile app with nativescript + Angular 8. Basically the app download a fat json object from the backend and then with multiple nested routing give the possibility to select a specific action.
The routing chain (each moduel is the child of the previous) is written below:
app-routing.module.ts -> main-routing.module.ts -> asset-routing.module.ts -> future-state.routing.module.ts
in the main.component.html is rendered a list of selectable assets generated dynamically from the json downloaded. When an asset is clicked a new list of selectable future-state generated dynamically from the json for the specific asset is shown. When a future-state is selected a list of selectable activities generated dynamically from the json for the specific future-state is shown. At the end the user can select the activity and the data is sent back to the backend.
In the selection phase everything is ok until the future-state item selection. When I try to select a future-state the code return me the Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: ....
future-state.commponent.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from "#angular/router";
import { RouterExtensions } from "nativescript-angular/router";
import { GlobalVariablesService } from '../../../_services/global-variables.service';
import { AndonPossibleIssueOpenStateDto } from '../../../_models/andon-possible-issue-open-state-dto';
#Component({
selector: 'ns-future-state',
templateUrl: './future-state.component.html',
styleUrls: ['./future-state.component.css']
})
export class FutureStateComponent implements OnInit {
id: number;
andonPossibleIssueOpenStateDto: AndonPossibleIssueOpenStateDto;
constructor(
private globalVariables: GlobalVariablesService,
private _route: ActivatedRoute,
private _routerExtensions: RouterExtensions
) { }
ngOnInit(): void {
const idFutureState = +this._route.snapshot.params.id;
this._route.params.subscribe(params => { this.id = params['id']; });
//this.andonPossibleIssueOpenStateDto=this.globalVariables.getAndonBotAssetPossibleStateIssueDto().find(function(element){return element.asset.id==idAsset}) as AndonPossibleIssueOpenStateDto;
}
onBackTap(): void {
this._routerExtensions.back();
}
}
future-state.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { FutureStateRoutingModule } from "./future-state-routing.module";
import { FutureStateComponent } from "./future-state.component";
import { ActivityComponent } from "./activity/activity.component";
#NgModule({
imports: [
NativeScriptCommonModule,
FutureStateRoutingModule
],
declarations: [
FutureStateComponent,
ActivityComponent
],
exports: [FutureStateComponent],
schemas: [
NO_ERRORS_SCHEMA
]
})
export class FutureStateModule { }
future-state-routing.module.ts
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { FutureStateComponent } from "./future-state.component";
import { ActivityComponent } from "./activity/activity.component";
const routes: Routes = [
{
path: "",
component: FutureStateComponent
},
{
path: "activity/:id",
component: ActivityComponent
}
];
#NgModule({
imports: [NativeScriptRouterModule.forChild(routes)],
exports: [NativeScriptRouterModule]
})
export class FutureStateRoutingModule { }
asset.component.ts
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from "#angular/router";
import { RouterExtensions } from "nativescript-angular/router";
import { GlobalVariablesService } from '../../_services/global-variables.service';
import { AndonBotAssetPossibleStateIssueDto } from '../../_models/andon-bot-asset-possible-state-issue-dto';
#Component({
selector: 'ns-asset',
templateUrl: './asset.component.html',
styleUrls: ['./asset.component.css']
})
export class AssetComponent implements OnInit {
id: number;
andonBotAssetPossibleStateIssueDto: AndonBotAssetPossibleStateIssueDto;
constructor(
private globalVariables: GlobalVariablesService,
private _route: ActivatedRoute,
private _routerExtensions: RouterExtensions
) { }
ngOnInit(): void {
const idAsset = +this._route.snapshot.params.id;
this.id = this._route.snapshot.params['id'];
console.log(this._route.snapshot.children);
console.log(this._route.snapshot.routeConfig);
this.andonBotAssetPossibleStateIssueDto=this.globalVariables.getAndonBotAssetPossibleStateIssueDto().find(function(element){return element.asset.id==idAsset}) as AndonBotAssetPossibleStateIssueDto;
console.log(this.andonBotAssetPossibleStateIssueDto.asset);
console.log(this._route.firstChild);
}
onBackTap(): void {
this._routerExtensions.back();
}
}
asset.coponent.html
<ActionBar class="action-bar">
<Label class="action-bar-title" [text]="andonBotAssetPossibleStateIssueDto.asset.name"></Label>
</ActionBar>
<StackLayout class="page page-content">
<ListView [items]="andonBotAssetPossibleStateIssueDto.possibleStateIssueDto.optionStateIssue" class="list-group">
<ng-template let-item="item">
<Label [nsRouterLink]="['./futureState', item.futureState.id]" [text]="item.futureState.name" class="list-group-item"></Label>
</ng-template>
</ListView>
</StackLayout>
asset.module.ts
import { NgModule, NO_ERRORS_SCHEMA } from "#angular/core";
import { NativeScriptCommonModule } from "nativescript-angular/common";
import { AssetRoutingModule } from "./asset-routing.module";
import { AssetComponent } from "./asset.component";
import { FutureStateModule } from "./future-state/future-state.module";
#NgModule({
imports: [
NativeScriptCommonModule,
AssetRoutingModule,
FutureStateModule
],
declarations: [
AssetComponent
],
exports: [AssetComponent],
schemas: [
NO_ERRORS_SCHEMA
]
})
export class AssetModule { }
asset-routing.module.ts
import { NgModule } from "#angular/core";
import { Routes } from "#angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";
import { NSEmptyOutletComponent } from "nativescript-angular";
import { AssetComponent } from "./asset.component";
import { FutureStateComponent } from "./future-state/future-state.component";
const routes: Routes = [
{
path: "",
component: AssetComponent
},
{
path: "futureState/:id",
component: FutureStateComponent
},
{
path: "futureState",
component: NSEmptyOutletComponent,
loadChildren: () => import("~/app/main/asset/future-state/future-state.module").then((m) => m.FutureStateModule)
}
];
#NgModule({
imports: [NativeScriptRouterModule.forChild(routes)],
exports: [NativeScriptRouterModule]
})
export class AssetRoutingModule { }
Below the error message:
Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'main/asset/698/futureState/6'
JS: Error: Cannot match any routes. URL Segment: 'main/asset/698/futureState/6'
JS:
at ApplyRedirects.push.../node_modules/#angular/router/fesm5/router.js.ApplyRedirects.noMatchError (file:///node_modules#angular\router\fesm5\router.js:2459:0) [angular]
JS: at CatchSubscriber.selector (file:///node_modules#angular\router\fesm5\router.js:2440:0) [angular]
JS: at CatchSubscriber.push.../node_modules/rxjs/_esm5/internal/operators/catchError.js.CatchSubscriber.error (file:///node_modules\rxjs_esm5\internal\operators\catchError.js:34:0) [angular]
JS: at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber._error (file:///node_modules\rxjs_esm5\internal\Subscriber.js:79:0) [angular]
JS: at MapSubscriber.push.../node_modules/rxjs/_esm5/internal/Subscriber.js.Subscriber.error (file:///data/data/org.nativescript.AndonMobile/fil...
The issue was that in the asset.component.html the link requested was /main/asset/[idAsset]/futureState/[idFutureState] instead the router dynamically generated in asset-routing.module.ts was something like /main/asset/futureState/[idFutureState].
I've modified the part:
{
path: "futureState/:id",
component: FutureStateComponent
}
with:
{
path: ":this.id/futureState/:id",
component: FutureStateComponent
}

Ionic 4 storage problem : No provider for Storage

I try to import storage mdule in my ionic project. but when i add providers Storage, The erro is changed. The error become 'can't resolved storege all : (?)'
How can i solve this error? can you help me please?
I wrote my codes below.
I watch this video :https://www.youtube.com/watch?v=h_IhS8QQjUA&list=PLNFwX8PVq5q7S-p_7zO99xdauhDsnMPw0&index=17&t=0s
App Module ts:
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { RouteReuseStrategy } from '#angular/router';
import { IonicModule, IonicRouteStrategy } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import {Storage} from '#ionic/storage';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { IonicStorageModule } from '#ionic/storage';
#NgModule({
declarations: [AppComponent],
entryComponents: [],
imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule,IonicStorageModule.forRoot()],
providers: [
StatusBar,
SplashScreen,
{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
],
bootstrap: [AppComponent]
})
export class AppModule {}
Page TS
import { Component, ViewChild } from "#angular/core";
import { StorageService, Item } from "../services/storage.service";
import { Platform, ToastController, IonList } from "#ionic/angular";
#Component({
selector: "app-home",
templateUrl: "home.page.html",
styleUrls: ["home.page.scss"]
})
export class HomePage {
items: Item[] = [];
newItem: Item = <Item>{};
#ViewChild("mylist") mylist: IonList;
constructor(
private storageService: StorageService,
private plt: Platform,
private toastController: ToastController
) {
this.plt.ready().then(() => {
this.loadItems();
});
}
loadItems() {
this.storageService.getItems().then(items => {
this.items = items;
});
}
addItem() {
this.newItem.modified = Date.now();
this.newItem.id = Date.now();
this.storageService.addItem(this.newItem).then(item => {
this.newItem = <Item>{};
this.showToast("Item Added");
this.loadItems();
});
}
updateItem(item:Item){
item.title='UPDATED:${item.title}';
item.modified=Date.now();
this.storageService.updateItem(item).then(item=>{
this.showToast("Item Updated");
this.loadItems();
});
}
deleteItem(item:Item){
this.storageService.deleteItem(item.id).then(item=>{
this.showToast("Item Deleted");
this.mylist.closeSlidingItems();
this.loadItems();
});
}
async showToast(msg){
const toast=await this.toastController.create({
message:msg,
duration:2000
});
toast.present();
}
}
Service
import { Injectable } from '#angular/core';
export interface Item{
id:number,
title:string,
value:string,
modified:number
}
const ITEMS_KEY="my-items";
#Injectable({
providedIn: 'root'
})
export class StorageService {
constructor(private storage:Storage) { }
addItem(item:Item):Promise<any>{
return this.storage.get(ITEMS_KEY).then((items:Item[])=>{
if(items){
items.push(item);
return this.storage.set(ITEMS_KEY,items);
}else{
return this.storage.set(ITEMS_KEY,[item]);
}
});
}
getItems():Promise<Item[]>{
return this.storage.get(ITEMS_KEY);
}
getItem(id:number){
}
updateItem(item:Item):Promise<any>{
return this.storage.get(ITEMS_KEY).then((items:Item[])=>{
if(!items || items.length==0){
return null;
}
let newItems:Item[]=[];
for (let i of items){
if(i.id==item.id){
newItems.push(item);
}else{
newItems.push(i);
}
}
return this.storage.set(ITEMS_KEY,newItems);
});
}
deleteItem(id:number):Promise<Item>{
return this.storage.get(ITEMS_KEY).then((items:Item[])=>{
if(!items || items.length==0){
return null;
}
let toKeep:Item[]=[];
for (let i of items){
if(i.id!=id){
toKeep.push(i);
}else{
//newItems.push(i);
}
}
return this.storage.set(ITEMS_KEY,toKeep);
});
}
}
In the StorageService file, you're injecting the storage like this:
constructor(private storage: Storage) { }
but I cannot see the Storage being imported in that file. So the Storage class injected in the constructor refers to the Web Storage API and not to the Ionic's Storage.
To fix that, please import the Storage from #ionic/storage:
import { Storage } from '#ionic/storage';
// ...
#Injectable({
providedIn: 'root'
})
export class StorageService {
constructor(private storage: Storage) { }
// ...
}
installing
npm install #ionic/storage
npm install #ionic/storage-angular
remember create your storage in the service
import { Storage } from '#ionic/storage';
constructor(private storage:Storage){
this.storage.create();
}
and import this in app.module
import { IonicStorageModule } from '#ionic/storage-angular';
import { Storage } from '#ionic/storage';
with storage in your providers
providers: [{ provide: RouteReuseStrategy},Storage],
ionic-storage angular

Ionic 3 : pass provider's variables to ion-input

I have this simple provider:
import { Injectable } from "#angular/core";
#Injectable()
export class DevicesService {
public check_string : any;
constructor(){
this.check_string = "Provider enabled";
}
getStatusString() { return this.check_string; }
}
and I am trying to pass that check_string variable to a ion-input in my home.ts:
<strong><ion-input round id="stringstatus" type="text" [(ngModel)]="stringstatus"></ion-input></strong>
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { DevicesService } from '../../providers/devicefactory/devicefactory';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public stateString : string;
constructor(public navCtrl: NavController, private deviceProvider : DevicesService) {
this.stateString = this.deviceProvider.check_string;
//this.stateString = this.deviceProvider.getStatusString();
}
}
I tried both two ways, direct pass variable and getting return function but once I run app it shows blank page.. what I could have missed?
Thanks a lot to all
Cheers!
Try using deviceProvider.getStatusString(). Without using this in constructor;
constructor(public navCtrl: NavController, private deviceProvider : DevicesService) {
this.stateString = deviceProvider.getStatusString();
}
You can directly set it in your ngModel :
[(ngModel)]="deviceProvider.check_string"
or
[(ngModel)]="deviceProvider.getStatusString()"
Hello Rameez and saperlipopette,
I tried as both of you obtaining this:
devicefactory.ts
import { Injectable } from "#angular/core";
//import { BluetoothLE } from '#ionic-native/bluetooth-le';
#Injectable()
export class DevicesService {
public ble_status : boolean;
public check_string : any;
// public BLE : BluetoothLE
constructor(){
this.ble_status = false;
//this.BLE.initialize();
//this.BLE.isEnabled().then(result => { this.ble_status = result.isEnabled; });
this.check_string = "Provider enabled";
}
getStatus() { return this.ble_status; }
getStatusString() { return this.check_string; }
enableBLE() {
//if (this.ble_status) this.BLE.enable(); else this.BLE.disable();
if (this.ble_status) this.check_string = "Provider enabled"; else this.check_string = "Provider disabled";
}
}
app.module.ts
import { NgModule, ErrorHandler } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { HoergerateApp } 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';
import { SettingsPage } from '../pages/settings/settings';
import { DevicesService } from '../providers/devicefactory/devicefactory';
#NgModule({
declarations: [
HoergerateApp,
AboutPage,
SettingsPage,
ContactPage,
HomePage,
TabsPage
],
imports: [
BrowserModule,
IonicModule.forRoot(HoergerateApp)
],
bootstrap: [IonicApp],
entryComponents: [
HoergerateApp,
AboutPage,
SettingsPage,
ContactPage,
HomePage,
TabsPage
],
providers: [
StatusBar,
SplashScreen,
DevicesService,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {
}
home.html
<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h2>Welcome to Ionic!</h2>
<p>
This starter project comes with simple tabs-based layout for apps
that are going to primarily use a Tabbed UI.
</p>
<p>
Take a look at the <code>src/pages/</code> directory to add or change tabs,
update any existing page or create new pages.
</p>
<p>
Check bluetooth status:<br>
<strong><ion-input round id="ble_state" type="text" [(ngModel)]="ble_state"></ion-input></strong>
</p>
</ion-content>
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { DevicesService } from '../../providers/devicefactory/devicefactory';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public ble_state : string;
constructor(public navCtrl: NavController, public deviceProvider : DevicesService) {
//this.ble_state = ( this.deviceService.ble_status ? "Bluetooth is enabled" : "BLuetooth is disabled" );
//this.ble_state = deviceProvider.check_string;
this.ble_state = deviceProvider.getStatusString();
}
}
Before I put also directly in [(ngModel)] but it goes for blank page..... I think it's related something about passing variables maybe because if I comment that:
this.ble_state = deviceProvider.getStatusString();
the app appears working...
Maybe it's related about ionic and cordova installation platforms or dependencies even if it didn't reported any errors during compilation?
Thanks

Self defined ionic2 component is not found

I have a login component with this code:
import { Injectable, Component } from '#angular/core';
import { Validators, FormBuilder } from '#angular/forms';
#Component({
selector: 'login',
templateUrl: 'login.html'
})
#Injectable()
export class LoginComponent {
login: any;
text: string;
constructor(private formBuilder: FormBuilder) {
this.text = 'Hello World';
}
ionViewLoaded() {
this.login = this.formBuilder.group({
title: ['', Validators.required],
description: [''],
});
}
doLogin(){
console.log(this.login.value)
}
}
I try to call it from the typescript file of page using
import { LoginComponent } from '../../component/login/login';
and
export class QuestionsPage {
constructor(public navCtrl: NavController, public loginComponent: LoginComponent ) {
}
Result is:
[13:23:46] typescript: src/pages/questions/questions.ts, line: 17
Cannot find name 'LoginComponent'.
which is the "constructor( public ..." line.
What do I do wrong?
Did you add your component to the #NgModules declarations array?
In your src/app/app.component.ts, add it like this:
import { LoginComponent } from '../../component/login/login';
#NgModule({
declarations: [
..
LoginComponent
..
]
})
You can read more here https://github.com/driftyco/ionic/blob/master/CHANGELOG.md#copying-your-project-to-a-new-project and here
https://angular.io/docs/ts/latest/guide/ngmodule.html