I am new to angularjs and ionic cordova. I am following the code given in this video lecture on ionic cordova BLE plugin module. I am trying to make this work using ionic 3 and have installed ionic cordova plugin for BLE.
https://www.youtube.com/watch?v=chfXawb_eVY&t=1898s
I have followed the exact instruction. Here's are my code files:
app.module.ts
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 { BLE } from '#ionic-native/ble';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
BLE
]
}) export class AppModule {}
home.ts
import { Component, NgZone } from '#angular/core';
import { NavController } from 'ionic-angular';
import { BLE } from '#ionic-native/ble';
import { ToastController } from 'ionic-angular';
import { setTimeout } from 'core-js/library/web/timers';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
devices: any[] = [];
statusMessage:string;
constructor(public navCtrl: NavController,
public toastCtrl: ToastController,
private ble: BLE,
private ngZone: NgZone) {
}
scan(){
this.setStatus('Scanning for bluetooth LE devices');
this.devices = [];
this.ble.scan([], 2).subscribe(
device=>this.onDeviceDiscovered(device),
error=>this.scanError(error)
);
setTimeout(this.statusMessage.bind(this),5000,'Scan Complete');
}
onDeviceDiscovered(device){
console.log('Scanning');
console.log('Discovered ' + JSON.stringify(device,null,2));
this.ngZone.run(()=>{
this.devices.push(device);
});
}
scanError(error) {
console.log('Check your bluetooth connection');
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
BLE Scanner
</ion-title>
<ion-buttons end>
<button ion-button (click)="scan()">
Scan
</button>
</ion-buttons>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<button ion-item *ngFor="let device of devices">
<h2>{{ device.name || 'Unnamed' }}</h2>
<p>{{ device.id }}</p>
<p>RSSI:{{ device.rssi }}></p>
</button>
</ion-list>
</ion-content>
The function scanError is not written in the video, I have wrote it.
This is the webview screenshot
this.setStatus function is not defined. However, in the video, the function has not been declared. I tried by declaring
setStatus:any
but the function still displayed the same message. Also, I am not able to get any messages in the console even if I remove the setStatus function.
I have included NgZone component at the beginning.
Is there any way to get this resolved or am I missing something?
You need to write a setStatus function in your code.
setStatus(message) {
console.log(message);
this.ngZone.run(() => {
this.statusMessage = message;
});
}
The code on the slides is abbreviated. The source code for the examples in the presentation is available on github https://github.com/don/ionic-ble-examples
Related
I currently have an Ionic app that creates an InAppBrowser pointing to a Website. I have deployed it to my Android phone, however there is a big issue.
Sometimes the app doesn’t work and opens the website with my default browser. Sometimes it does work and opens the website in the app using InAppBrowser.
I have tried using the different targets self, blank, system and different Android phones, but nothing fully works.
I am really confused and tried a number of things, any ideas?
Thanks in advance.
Below are my code files:
home.html
<ion-header>
<ion-navbar color="dark">
<ion-title>
InAppBrowser
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
InAppBrowser Not Displayed.
</ion-content>
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { InAppBrowser, InAppBrowserOptions } from "#ionic-native/in-app-browser";
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController, private inAppBrowser: InAppBrowser) {
const options: InAppBrowserOptions = {
toolbar: 'no',
location: 'no',
zoom: 'no'
}
const browser = this.inAppBrowser.create("https://www.awebsite.co.uk", '_self', options);
}
}
app.module.ts
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 { HomePage } from '../pages/home/home';
import { InAppBrowser } from '#ionic-native/in-app-browser';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
InAppBrowser
]
})
export class AppModule {}
Did you try to wait the "platform" to be "ready" to use?
https://ionicframework.com/docs/api/platform/Platform/
export class HomePage {
constructor(public navCtrl: NavController, private inAppBrowser: InAppBrowser, public platform: Platform) {
const options: InAppBrowserOptions = {
toolbar: 'no',
location: 'no',
zoom: 'no'
}
this.platform.ready().then( () => {
const browser = this.inAppBrowser.create("https://www.awebsite.co.uk", '_self', options);
})
}
}
Doing this, the code will only run when the app is ready. In the device environment, when Cordova is ready to be used.
I am very new to Ionic and Cordova, for the last couple of days I am trying to download an image that I have upload in firebase storage. I want to transfer the image and store it in my mobile device through my mobile application. I have installed all the plugins needed to do that. I have created two buttons. The first button is to display the image in my application and the second button is to download the image in my device. The source code for that is in my storage.html
<ion-header>
<ion-navbar>
<ion-title>storage</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<button ion-button (click)="display()">Display</button>
<button ion-button (click)="download()">Download</button>
<img src="{{imgsource}}">
</ion-content>
The functionality is in my storage.ts
import { Component, NgZone } from '#angular/core';
import { NavController, Platform, AlertController } from 'ionic-angular';
//import {File,Transfer} from 'ionic-native';
import {FileTransferObject } from '#ionic-native/file-transfer';
import {TransferObject} from '#ionic-native/transfer';
import {Transfer} from '#ionic-native/transfer';
import {File} from '#ionic-native/file';
import firebase from 'firebase';
declare var cordova: any;
#Component({
selector: 'storage-home',
templateUrl: 'storage.html',
providers: [Transfer, TransferObject, File]
})
export class StoragePage {
storageDirectory: string = '';
fileTransfer: FileTransferObject;
nativepath: any;
firestore = firebase.storage();
imgsource: any;
constructor(public navCtrl: NavController, public platform: Platform, public alertCtrl: AlertController, public zone: NgZone) {
this.platform.ready().then(() => {
// make sure this is on a device, not an emulation (e.g. chrome tools device mode)
if(!this.platform.is('cordova')) {
return false;
}
if (this.platform.is('ios')) {
this.storageDirectory = cordova.file.documentsDirectory;
}
else if(this.platform.is('android')) {
this.storageDirectory = cordova.file.dataDirectory;
}
else {
// exit otherwise, but you could add further types here e.g. Windows
return false;
}
});
}
display() {
this.firestore.ref().child('image.jpg').getDownloadURL().then((url) => {
this.zone.run(() => {
this.imgsource = url;
this.fileTransfer.download(url,'image.jpg').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
})
})
}
downlad() {
this.firestore.ref().child('image.jpg').getDownloadURL().then((url) => {
this.zone.run(() => {
this.imgsource = url;
this.fileTransfer.download(url,cordova.file.dataDirectory +'image.jpg').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
// handle error
});
})
})
}
}
The display button works perfectly as I can see my image when I install the application on my device. The problem though is with the download button as nothing is happening and I don’t know if it’s working as I can’t find my image anywhere in my device. Can anyone please guide me?
Thanks in regards
It looks like you may have a typo on your download function name. In the HTML module you refer to download() and in your code your function is labeled as downlad.
I am trying to load a local json file into my service component to fill a template with it. The http call works always in my browser but bundled with cordova it only works if I use the tag directly instead of with the routing module. :S
in my nav component I got
ngOnInit() {
alert('enter on init')
this.chatService.getJSON().subscribe(data => {
this.Questionaire = data;
console.log('fill Questionaire');
console.log(this.Questionaire.UserChatContent);
this.createNewItem(this.Questionaire);
}, err => {
console.log('error');
err.forEach(e => alert(e) );
});
console.log('leave on init');
}
this is my routing module
import { NgModule } from '#angular/core';
import { CommonModule } from '#angular/common';
import { RouterModule, Routes } from '#angular/router';
import {ChatViewComponent} from './chat-view/chat-view.component';
import {DailyTrainingComponent} from './daily-training/daily-training.component';
import {HttpClient, HttpClientModule} from '#angular/common/http';
const routes: Routes = [
{ path: 'chat', component: ChatViewComponent },
{ path: 'training', component: DailyTrainingComponent }
];
#NgModule({
imports: [
CommonModule,
RouterModule.forRoot(routes)
],
exports: [ RouterModule ]
})
export class AppRoutingModule { }
now the Issue:
//the following code works fine in cordova on android
//and in my browser window (firefox and chrome)
<div class="fullScreen">
<app-chat-view></app-chat-view>
</div>
whereas
// works in browser like its supposed to
// but in cordova on android the http call in the ngOnInit() in the component always fails :S
<div class="fullScreen">
<nav id="navStyle">
<a class="navElem" routerLink="/fd" (click)="navActive(0)"><div class="navOne"></div></a>
<a class="navElem" routerLink="/training" (click)="navActive(1)"><div class="navTwo"></div></a>
<a class="navElem" routerLink="/chat" (click)="navActive(2)"><div class="navChat"></div></a>
<a class="navElem" routerLink="/df" (click)="navActive(3)"><div class="navFour"></div></a>
<a class="navElem" routerLink="/d" (click)="navActive(4)"><div class="navFive"></div></a>
</nav>
<router-outlet></router-outlet>
</div>
I am new to angular 5 so I really hope this is not a stupid question. :S
thanks in advance :D
(here the service I am using HttpClient and HttpClientModule)
import { Injectable } from '#angular/core';
import {Observable} from 'rxjs/Observable';
import {HttpClient, HttpClientModule} from '#angular/common/http';
#Injectable()
export class ChatService {
Questionaire: object;
constructor(private http: HttpClient) {
this.getJSON().subscribe(data => {
alert('Object: ' + data.UserChatContent);
this.Questionaire = data;
});
}
public getJSON(): Observable<any> {
return this.http.get('./assets/questionaire.json');
}
}
Hello I am trying to follow a tutorial about implementing sqlite in an ionic app: https://www.youtube.com/watch?v=E6h8PFHMLIU
I did everything as proposed in the turoial but still when I run the application in the android emulator (ionic cordova build android; ionic cordova run android) it does not display the data from the database as in the video. What am I doing wrong? Below you can see the code
app.module.ts
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 { HomePage } from '../pages/home/home';
import { IonicStorageModule } from '#ionic/storage';
import { HttpModule } from '#angular/http';
import { DatabaseProvider } from '../providers/database/database';
import { SQLitePorter } from '#ionic-native/sqlite-porter';
import { SQLite } from '#ionic-native/sqlite';
#NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
HttpModule,
IonicStorageModule.forRoot(),
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler},
DatabaseProvider,
SQLitePorter,
SQLite
]
})
export class AppModule {}
database.ts
import { Injectable } from '#angular/core';
import { Platform } from 'ionic-angular';
import { SQLite, SQLiteObject } from '#ionic-native/sqlite';
import { SQLitePorter } from '#ionic-native/sqlite-porter';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import { BehaviorSubject } from 'rxjs/Rx';
import { Storage } from '#ionic/storage';
#Injectable()
export class DatabaseProvider {
database: SQLiteObject;
private databaseReady: BehaviorSubject<boolean>;
constructor(public sqlitePorter: SQLitePorter, private storage: Storage, private sqlite: SQLite, private platform: Platform, private http: Http) {
this.databaseReady = new BehaviorSubject(false);
this.platform.ready().then(() => {
this.sqlite.create({
name: 'developers.db',
location: 'default'
})
.then((db: SQLiteObject) => {
this.database = db;
this.storage.get('database_filled').then(val => {
if (val) {
this.databaseReady.next(true);
} else {
this.fillDatabase();
}
});
});
});
}
fillDatabase() {
this.http.get('assets/dummyDump.sql')
.map(res => res.text())
.subscribe(sql => {
this.sqlitePorter.importSqlToDb(this.database, sql)
.then(data => {
this.databaseReady.next(true);
this.storage.set('database_filled', true);
})
.catch(e => console.error(e));
});
}
addDeveloper(name, skill, years) {
let data = [name, skill, years]
return this.database.executeSql("INSERT INTO developer (name, skill, yearsOfExperience) VALUES (?, ?, ?)", data).then(data => {
return data;
}, err => {
console.log('Error: ', err);
return err;
});
}
getAllDevelopers() {
return this.database.executeSql("SELECT * FROM developer", []).then((data) => {
let developers = [];
if (data.rows.length > 0) {
for (var i = 0; i < data.rows.length; i++) {
developers.push({ name: data.rows.item(i).name, skill: data.rows.item(i).skill, yearsOfExperience: data.rows.item(i).yearsOfExperience });
}
}
return developers;
}, err => {
console.log('Error: ', err);
return [];
});
}
getDatabaseState() {
return this.databaseReady.asObservable();
}
}
home.ts
import { DatabaseProvider } from './../../providers/database/database';
import { Component } from '#angular/core';
import { NavController, Platform } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
developer = {};
developers = [];
constructor(public navCtrl: NavController, private databaseprovider: DatabaseProvider, private platform: Platform) {
this.databaseprovider.getDatabaseState().subscribe(rdy => {
if (rdy) {
this.loadDeveloperData();
}
})
}
loadDeveloperData() {
this.databaseprovider.getAllDevelopers().then(data => {
this.developers = data;
})
}
addDeveloper() {
this.databaseprovider.addDeveloper(this.developer['name'], this.developer['skill'], parseInt(this.developer['yearsOfExperience']))
.then(data => {
this.loadDeveloperData();
});
this.developer = {};
}
}
home.html
<ion-header>
<ion-navbar>
<ion-title>
Developer Data
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-item>
<ion-label stacked>What's your name?</ion-label>
<ion-input [(ngModel)]="developer.name" placeholder="Developer Name"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>What's your special skill?</ion-label>
<ion-input [(ngModel)]="developer.skill" placeholder="Special Skill"></ion-input>
</ion-item>
<ion-item>
<ion-label stacked>How long have you been working?</ion-label>
<ion-input [(ngModel)]="developer.yearsOfExperience" placeholder="Years of experience"></ion-input>
</ion-item>
<button ion-button full (click)="addDeveloper()">Add Developer Info</button>
<ion-list>
<ion-item *ngFor="let dev of developers">
<h2>{{ dev.name }}</h2>
<p>{{ dev.yearsOfExperience }} years of {{ dev.skill }} Experience!</p>
</ion-item>
</ion-list>
</ion-content>
CLI:
node -v 6.11.2
cordova -v 6.5.0
ionic -v 3.9.2
Create an ionic tabs project with only the homepage(Manually deleted):
ionic start demo1 tabs
then create two pages use the cmd:
ionic g page Oneself
ionic g page Setting
this is app.module.ts code:
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 { HomePage } from '../pages/home/home';
import { TabsPage } from '../pages/tabs/tabs';
//import { SettingPage } from "../pages/setting/setting";
//import { OneselfPage } from "../pages/oneself/oneself";
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
#NgModule({
declarations: [
MyApp,
HomePage,
TabsPage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage,
TabsPage
],
providers: [
StatusBar,
SplashScreen,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
this is oneself.module.ts like this:
import { NgModule } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { OneselfPage } from './oneself';
#NgModule({
declarations: [
OneselfPage,
],
imports: [
IonicPageModule.forChild(OneselfPage),
],
exports:[
OneselfPage
]
})
export class OneselfPageModule {}
this is oneself.ts File Code like this:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
/**
* Generated class for the OneselfPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
#IonicPage()
#Component({
selector: 'page-oneself',
templateUrl: 'oneself.html',
})
export class OneselfPage {
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad OneselfPage');
}
}
SettingPage Same as above;
this is tabs.ts code :
import { Component } from '#angular/core';
import { HomePage } from '../home/home';
#Component({
templateUrl: 'tabs.html'
})
export class TabsPage {
tab1Root = HomePage;
tab2Root = "OneselfPage";//class name
tab3Root = "SettingPage";//class name
constructor() {
}
}
I know that lazy loading has several key points, such as declaring #ionicpage (), #ngmodule, IonicPageModule. ForChild (pageName)... I have such declarations in my code, but lazy loads don't work and the errors are as follows:
This is the first line error, and I don't know if it's related to lazy loading
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
The following error must have something to do with lazy loading :
Error {rejection: Error, promise: t, zone: r, task: t, stack: <accessor>, …}
message: "Uncaught (in promise): Error: Cannot find module '../pages/oneself/oneself.module'.
Error: Cannot find module '../pages/oneself/oneself.module'
at file:///android_asset/www/build/main.js:65357:9
at t.invoke
See screen capture :
https://i.stack.imgur.com/AGTVN.jpg
Can someone help me answer this question?
Problem solved, the cordova ionic installed with cnpm has the problem,dont use cnpm install , use npm install ,the lazy load is run.
CLI:
node -v 8.2.1
cordova -v 7.0.1
ionic -v 3.9.2
I have followed what you have described
ionic start demo1 tabs
ionic g page Oneself
ionic g page Setting
I was unable to reproduce any of the errors that you were stating
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
or
Error {rejection: Error, promise: t, zone: r, task: t, stack: <accessor>, …}
message: "Uncaught (in promise): Error: Cannot find module '../pages/oneself/oneself.module'.
Error: Cannot find module '../pages/oneself/oneself.module'
at file:///android_asset/www/build/main.js:65357:9
at t.invoke
If you want to compare against my reproduction of your scenario you can do so, hope this helps