i want to check for network connectivity in my ionic app, but its not working.
Here's the code
ionViewDidEnter(){
let connectSubscription=this.network.onDisconnect().subscribe(() => {
console.log(2)
console.log('live network was disconnected :-(');
});
connectSubscription.unsubscribe();
let disconnectSubscription=this.network.onConnect().subscribe(() => {
console.log(4)
console.log('live network connected!');
});
disconnectSubscription.unsubscribe();
}
I want to know when my network is online and when the network does offline i should know but this code does noting, it outputs noting to the console, i am using the latest ionic 6.9
maybe it is better to check additional the network-type
In general do the following:
implement it as a service
inject the service in the module
NetworkService.ts
import { Injectable } from '#angular/core';
#Injectable()
export class NetworkService{
constructor(public network: Network) {
}
checkOnlineStat(){
if (this.network.type === 'none'){
return "offline";
}else if(this.network.type === 'wifi'){
return "online";
}
}
}
component.ts:
constructor(public networkSrv: NetworkService) {}
public onViewDidLoad() {
if (networkSrv.checkOnlineStat === 'online') {
// online
}
}
Use the Service where you need it. You can generate a new service by cli.
Related
I'm trying to get the "#capacitor/push-notifications": "^1.0.8" to work.
Everything seems fine and all the solutions i have found looking around are not working for me.
I have tried:
Editing MainActivity.java
Changing Gradle files.
But no luck with the things i found.
Anyone got an idea how to fix this. ( also trying this on an emulator and https server )
I did read that it would not work on https but not sure why.
Do this when your app is starting
import {
PushNotifications,
Token,
ActionPerformed,
PushNotificationSchema
} from '#capacitor/push-notifications';
...
async initPush(): Promise<void> {
if (this.platform.is('hybrid')) {
await this.registerPush();
}
}
private async registerPush() {
const permission = await PushNotifications.requestPermissions();
if (permission.receive === 'granted') {
// Register with Apple / Google to receive push via APNS/FCM
await PushNotifications.register();
} else {
// No permission for push granted
console.log("error");
}
}
Also if you are using Capacitor 3, your MainActivity.java should look like this:
package com.your.package.name;
import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import com.getcapacitor.Plugin;
import java.util.ArrayList;
public class MainActivity extends BridgeActivity {
}
I'm learning Angular 9 and have gone through the Tour of Heroes app and tutorial. I've used this tutorial as a base to add new features such as CRUD operations on a remote resource and I have added #ng-bootstrap/ng-bootstrap to the projects but I cannot get angular-bootstrap-toggle to work.
The instructions on Bootstrap Toggle don't match what I have learned so far and I can't find a solution anywhere.
For example, I don't know how this command angular.module('myApp', ['ui.toggle']); fits in with Angular 9 and the tutorial I have used.
How can I get the system to call onChange() when I click the toggle?
angular.json
"styles": [
"node_modules/bootstrap/dist/css/bootstrap.min.css",
"node_modules/bootstrap4-toggle/css/bootstrap4-toggle.min.css",
"src/styles.css"
],
"scripts": [
"node_modules/jquery/dist/jquery.min.js",
"node_modules/bootstrap/dist/js/bootstrap.bundle.js",
"node_modules/bootstrap4-toggle/js/bootstrap4-toggle.min.js"
]
navigation-bar.component.html This displays correctly and toggles as expected
<input id="local-browse" (change)="onChange()" type="checkbox" checked="" data-toggle="toggle" data-on="Local" data-off="Remote" data-onstyle="success" data-offstyle="danger" data-size="sm">
navigation-bar.component.ts If I put in a standard checkbox the onChange() does work as expected but not with angular-bootstrap-toggle
import { Component, OnInit } from '#angular/core';
declare var $: any;
#Component({
selector: 'app-navigation-bar',
templateUrl: './navigation-bar.component.html',
styleUrls: ['./navigation-bar.component.css'],
})
export class NavigationBarComponent implements OnInit {
localUrl = 'http://192.168.253.53';
remoteUrl = 'https://remoteaddress.com';
local = true;
constructor() {}
ngOnInit(): void {
$(document).ready(() => {
console.log('The document ready for jQuery!');
});
}
onChange() {
if (this.local === true) {
this.local = false;
} else {
this.local = true;
}
}
}
I dont think it is compatible with Angular 2+ (or at least angular 9).
You may like to use ng-toggle from https://www.npmjs.com/package/#nth-cloud/ng-toggle
Which is tested on Angular 9.
More information about installation in https://nth-cloud.github.io/ng-toggle/#/home
What i am trying to do-
i am setting (again) some key (which are set at some other point in my application i.e, Login )value pairs in local storage when a function is called.
similar to reset password.
and it works fine just the problem is that when on the same page if i access those items after resetting them it shows undefined. but when i do login again those values are changed and shows the latest values.
i also tried running on android device and in ionic serve and ionic lab . it never worked.
constructor(public navCtrl: NavController,
public navParams: NavParams,
public apiConnect:ApiIntegrationProvider,
public loadingCtrl:LoadingController,
public toastCtrl:ToastController,
public storage: Storage) {
console.log(this.user_name)
this.fetchProfile();
}
fetchProfile(){
this.user_role=localStorage.getItem("userRole");
this.user_name=localStorage.getItem("userName");
this.user_Email=localStorage.getItem("userEmail");
this.user_Mobile=localStorage.getItem("userMobile");
this.user_Avatar=localStorage.getItem("userAvatar");
this.user_Language=localStorage.getItem("userLanguage");
this.company_name=localStorage.getItem("companyName");
this.company_email=localStorage.getItem("companyEmail");
this.company_punch=localStorage.getItem("companyPunch");
this.company_url=localStorage.getItem("companyUrl");
console.log("user data")
console.log("company name", this.company_name,"email",this.company_email,"punch",this.company_punch,"website", this.company_url,"language", this.user_Language);
if(this.user_Language=='pt'){
this.language="Portuguese"
}else{
this.language="English"
}
if(this.user_role=='25'){
this.role='Inspector';
}else if(this.user_role=='35'){
this.role='Team Lead';
}else if(this.user_role=='45'){
this.role='Moderator';
}else if(this.user_role=='55'){
this.role='Administrator';
}else if(this.user_role=='65'){
this.role='Super Administrator';
}
}
editProfile(){
console.log(this.decideEditProfile);
console.log("edit profile function")
this.decideEditProfile=true;
}
SaveProfile(){
console.log(this.decideEditProfile);
console.log("edit profile function")
this.decideEditProfile=false;
this.useredit();
}
ionViewDidLoad() {
console.log('ionViewDidLoad ProfilePage');
}
showToast(position: string) {
let toast = this.toastCtrl.create({
message: this.editStatus.message,
duration: 2000,
position: 'top'
});
toast.present(toast);
}
useredit() {
const loader = this.loadingCtrl.create({
content: "Please wait...",
duration: 3000
});
loader.present();
let passingValue = {
"user_id": '3',
"inputName": 'James Red',
"inputEmail":'moderator#gmail.com.in',
"inputPassword":'123456'
}
this.apiConnect.postEditProfile(
JSON.stringify(passingValue)).subscribe((data) => {
console.log("login api "+JSON.stringify(data));
this.editStatus = data;
if (this.editStatus.status == "success") {
localStorage.removeItem("userName");
localStorage.removeItem("userEmail");
localStorage.removeItem("userMobile");
localStorage.removeItem("userAvatar");
localStorage.removeItem("userLanguage");
localStorage.setItem("userName",this.editStatus.Profile.fullName);
localStorage.setItem("userEmail",this.editStatus.Profile.emailAddress);
localStorage.setItem("userMobile",this.editStatus.Profile.mobile);
localStorage.setItem("userAvatar",this.editStatus.Profile.avatar);
localStorage.setItem("userLanguage",this.editStatus.Profile.languagePreference);
this.showToast('top');
this.navCtrl.push("DashBoardPage");
}
else {
this.showToast('top');
}
loader.dismiss();
})
}
From your question you are trying to say that even after updating the localstorage you are getting the old value or undefined.
So it might be possible that the data which you are returning may be null or empty. You have to carefully debug your application because localstorage do not work this same way. Do a console test.
Also in this piece of code :
if (this.editStatus.status == "success") {
localStorage.removeItem("userName");
localStorage.removeItem("userEmail");
localStorage.removeItem("userMobile");
localStorage.removeItem("userAvatar");
localStorage.removeItem("userLanguage");
localStorage.setItem("userName",this.editStatus.Profile.fullName);
localStorage.setItem("userEmail",this.editStatus.Profile.emailAddress);
localStorage.setItem("userMobile",this.editStatus.Profile.mobile);
localStorage.setItem("userAvatar",this.editStatus.Profile.avatar);
localStorage.setItem("userLanguage",this.editStatus.Profile.languagePreference);
this.showToast('top');
this.navCtrl.push("DashBoardPage");
}
You do not have to remove the items unnecessarily you can just set the localstorage and the old values will be replaced by the new values.
I hope this helps you. Thanks!
I am investigating using Ionic 4/ Capacitor to target Windows via the Electron option, for an application where I want to use SQLite.
Using the Ionic Native SQLite plugin, which wraps this Cordova plugin, out of the box, as far as I can see, the Windows support is for UWP, and not Desktop, which runs using Electron in Ionic Capacitor wrapper.
My plan, was to see if I could use Electron SQLite package, and then call this from my Ionic application by making a wrapper class for the Ionic native similar to what I used to get browser support by following this tutoral
If I can call the Electron code from my Ionic app, then I can't see why this wouldn't work.
So, my question here is, can I call code (I will add functions to use the SQlite) I add to the hosting Electron application from within the Ionic (web) code? And if so, how?
Thanks in advance for any help
[UPDATE1]
Tried the following...
From an Ionic page, I have a button click handler where I raise an event..
export class HomePage {
public devtools() : void {
let emit = new EventEmitter(true);
emit.emit('myEvent');
var evt = new CustomEvent('myEvent');
window.dispatchEvent(evt);
}
Then within the Electron projects index.js, I tried..
mainWindow.webContents.on('myEvent', () => {
mainWindow.openDevTools();
});
const ipc = require('electron').ipcMain
ipc.on('myEvent', (ev, arg) => {
mainWindow.openDevTools();
});
But neither worked.
I should mention I know very little about Electron. This is my first exposure to it (via Capacitor)
In case someone is interested, this is how I solved this.
Im am using Ionic 4 / Capacitor + Vue 3.
In my entry file (app.ts) I have declared a global interface called Window as follows:
// app.ts
declare global { interface Window { require: any; } }
Then, I have written the following class:
// electron.ts
import { isPlatform } from '#ionic/core';
export class Electron
{
public static isElectron = isPlatform(window, 'electron');
public static getElectron()
{
if (this.isElectron)
{
return window.require('electron');
}
else
{
return null;
}
}
public static getIpcRenderer()
{
if (this.isElectron)
{
return window.require('electron').ipcRenderer;
}
else
{
return null;
}
}
public static getOs()
{
if (this.isElectron)
{
return window.require('os');
}
else
{
return null;
}
}
}
And I use it like this:
//electronabout.ts
import { IAbout } from './iabout';
import { Plugins } from '#capacitor/core';
import { Electron } from '../utils/electron';
export class ElectronAbout implements IAbout
{
constructor() { }
public async getDeviceInfo()
{
let os = Electron.getOs();
let devInfo =
{
arch: os.arch(),
platform: os.platform(),
type: os.type(),
userInfo: os.userInfo()
};
return devInfo;
}
public async showDeviceInfo()
{
const devInfo = await this.getDeviceInfo();
await Plugins.Modals.alert({ title: 'Info from Electron', message: JSON.stringify(devInfo) });
}
}
This is working but, of course, I still need to refactor the Electron class (electron.ts). Probably using the singleton pattern is a better idea.
I hope this helps.
Update
You can communicate from the render process with your main process (index.js) like this:
//somefile.ts
if (Electron.isElectron)
{
let ipc = Electron.getIpcRenderer();
ipc.once('hide-menu-button', (event) => { this.isMenuButtonVisible = false; });
}
//index.js
let newWindow = new BrowserWindow(windowOptions);
newWindow.loadURL(`file://${__dirname}/app/index.html`);
newWindow.webContents.on('dom-ready', () => {
newWindow.webContents.send('hide-menu-button');
newWindow.show();
});
I dug into this yesterday and have an example for you using angular(this should apply to ionic too).
in your service declare require so we can use it
//Below your imports
declare function require(name:string);
Then in whatever function you want to use it in:
// Require the ipcRenderer so we can emit to the ipc to call a function
// Use ts-ignore or else angular wont compile
// #ts-ignore
const ipc = window.require('electron').ipcRenderer;
// Send a message to the ipc
// #ts-ignore
ipc.send('test', 'google');
Then in the created index.js within the electron folder
// Listening for the emitted event
ipc.addListener('test', (ev, arg) => {
// console.log('ev', ev);
console.log('arg', arg);
});
Its probably not the correct way to access it but its the best way i could find. From my understanding the ipcRenderer is used for when you have multiple browsers talking to each other within electron. so in our situation it enables our web layer to communicate with the electron stuff
I need to submit a form coming from a payment gateway. Our backend guy asks me to either put the innerHtml and send after it rendered. I got it to work on Chrome, but failed on Firefox.
Now I'm trying to fix it on our testing environment, the backend added a JSON return of all the properties I need to replicate the form he was sending me so I can make my own form. But still failing to submit on Firefox.
Does someone have the same experience? Please shed me some light.
Is there any Firefox specific fixes I need to know?
Below is the working code on Chrome and Safari
import { Component, OnInit, AfterViewInit, ViewChild, ElementRef,DoCheck, ViewChildren, QueryList } from '#angular/core';
import { BrowserModule, DomSanitizer, SafeResourceUrl, SafeUrl} from '#angular/platform-browser';
import { PaymentService } from '../../_services/payment.service';
import { Loader } from '../../_services/loader.service';
#Component({
selector: 'bdf-payment-form',
templateUrl: './payment-form.component.html',
styleUrls: ['./payment-form.component.scss']
})
export class PaymentFormComponent implements OnInit,DoCheck, AfterViewInit {
form : SafeResourceUrl;
// #ViewChild('paymentFormContainer') container: ElementRef;
#ViewChild('paymentForm') myForm: ElementRef;
loader;
constructor(private paymentService:PaymentService,
private sanitizer: DomSanitizer,
private loaderService: Loader,
private elRef:ElementRef) { }
ngDoCheck(){
}
ngOnInit() {
console.log(this.paymentService.paymentForm);
this.paymentService.paymentForm ? this.form = this.sanitizer.bypassSecurityTrustHtml(this.paymentService.paymentForm) : null
this.loader = true;
}
ngAfterViewInit() {
let test;
if(this.form){
test = this.elRef.nativeElement.querySelector('form')
console.log(test)
test.submit();
}
}
}
You shouldn't use submit() method to avoid redirection with page refresh.
The http service is used to submit the form data serialized to json from the form. If you have form elements bound to the model then it would be easier to send the model back to the backend.