Quantcast
Channel: Ionic Forum - Latest topics
Viewing all 71530 articles
Browse latest View live

ngModel question

$
0
0

@Doomkin wrote:

Hi, I have a quite simple app where ppl can add Tasks.

add-task.page.html is the following

<ion-content padding>
  <ion-list>
      <ion-item>
        <ion-label position="stacked">Task Title</ion-label>
        <ion-input type="text" ([ngModel])="task_title"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="stacked">Task Description</ion-label>
        <ion-input type="text" ([ngModel])="task_description"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label position="stacked">Task last date</ion-label>
        <ion-datetime min="2019" display-format="DD/MM/YYYY" ([ngModel])="task_last_date"></ion-datetime>
      </ion-item>
  </ion-list>
  <ion-button expand="block" shape="round" color="danger" (click)="addTask()">Add Task</ion-button>
</ion-content>

add-task.page.ts is the follwing

import { Component, OnInit } from '@angular/core';
import * as firebase from 'firebase';
import { ToastController, NavController } from '@ionic/angular';

@Component({
  selector: 'app-add-task',
  templateUrl: './add-task.page.html',
  styleUrls: ['./add-task.page.scss'],
})
export class AddTaskPage implements OnInit {

  task_title: string;
  task_description: string;
  task_last_date: Date;
  task_owner: string;

  constructor(private toastCtrl: ToastController, private navCtrl: NavController) {
    this.task_owner = firebase.auth().currentUser.uid;

   }

  ngOnInit() {
  }

  addTask() {
    console.log(this.task_title);
    console.log(this.task_description);
    console.log(this.task_last_date);
    console.log(this.task_owner);

  }
}

When I click the button to add the task, in the console log I see 3 undefineds and only this.task_owner variable is populated.

Am I missing something stupid?

Thanks!

Posts: 2

Participants: 2

Read full topic


Ionic cordova in app phone call to a number but without launching dialer

$
0
0

@ubaidgul wrote:

I want to dial a number(speaker phone) from a page in my App and I want to keep that page in front of the user. I don’t want to open the builtin App to dial that number. I tried cordova plugin Call number but it takes me to builtin call App.

Posts: 1

Participants: 1

Read full topic

Custom notification sound not working, right filepath!

$
0
0

@SaltyPotato wrote:

My Environment

  • Plugin version: 0.9.0-beta.2
  • Platform: Android
  • OS version: 8.0.x
  • Device manufacturer / model: Samsung Galaxy s8
  • Cordova version (cordova -v): 4.2.1
  • Cordova platform version (cordova platform ls): 7.1.4
  • Plugin config: none
  • Ionic Version: 3.9.2

Expected Behavior

Using:

this.localNotifications.schedule({
                    id: 1,
                    text: 'You have arrived',
                    sound: 'file://assets/sounds/alerts/arrival.mp3',
                    data: { secret: 'hellloo' },
                    vibrate: true
                });

I want to display a notification with a custom sound
Located in src/assets/sounds/alerts/...

Actual Behavior

I’ve tried every possible filepath (I think) however it still plays the default Samsung Galaxy s8 notification sound.

Context

Explained above.

Debug logs

Logcat output:

02-28 17:38:06.354  3779  3779 D EdgeLightingManager: showForNotification : isInteractive=true, isHeadUp=false, color=0, sbn = StatusBarNotification(pkg=io.ionic.starter user=UserHandle{0} id=1 tag=null key=0|io.ionic.starter|1|null|10203: Notification(channel=default-channel-id pri=0 contentView=null vibrate=null sound=null tick defaults=0x0 flags=0x11 color=0x00000000 number=0 vis=PUBLIC semFlags=0x0 semPriority=0 semMissedCount=0))
02-28 17:38:06.354  3779  3779 D EdgeLightingPolicyManager: putNotification tickerText:true,titleText:true,text:true,sub:falsecn= + null
02-28 17:38:06.354  3779  3779 D EdgeLightingPolicyManager.NotificationGroup: updateNotificationData put :0|io.ionic.starter|1|null|10203,size=7
02-28 17:38:06.354  3779  3779 D EdgeLightingPolicyManager.NotificationGroup: 0|io.ionic.starter|1|null|10203:NotificationData time=1551371886354,
02-28 17:38:06.354  3779  3779 D EdgeLightingPolicyManager.NotificationGroup: 0|android|40|null|1000:NotificationData time=1551371251595,
02-28 17:38:06.355  3779  3779 D EdgeLightingPolicyManager.NotificationGroup: 0|com.rolflex.mobCSRApp|6|null|10156:NotificationData time=1551291051811,
02-28 17:38:06.355  3779  3779 D EdgeLightingPolicyManager.NotificationGroup: 0|com.wssyncmldm|1|null|1000:NotificationData time=1551349895823,
02-28 17:38:06.355  3779  3779 D EdgeLightingPolicyManager.NotificationGroup: 0|com.google.android.apps.maps|g:atn_group:NotificationData time=1551371775363,
02-28 17:38:06.355  3779  3779 D EdgeLightingPolicyManager.NotificationGroup: 0|com.rolflex.mobCSRApp|-574543954|null|10156:NotificationData time=1551291051833,
02-28 17:38:06.355  3779  3779 D EdgeLightingPolicyManager.NotificationGroup: 0|com.android.vending|874755343|null|10043:NotificationData time=1551314492705,
02-28 17:38:06.355  3779  3779 D EdgeLightingPolicyManager.NotificationGroup: 0|com.android.settings|9|null|1000:NotificationData time=1550852356484,
02-28 17:38:06.355  3779  3779 D EdgeLightingManager: showForNotificationScreenOn : return false by isAcceptableApplication.
02-28 17:38:06.365  3779  3779 I AccessibilityManagerService: semOnLightNotification(null), bIsFlashOn : false
02-28 17:38:06.372  4196  4196 D StatusBar: addNotification key=0|io.ionic.starter|1|null|10203 fullscreen:false
02-28 17:38:06.460  3426 15233 V NuPlayer: onSourceNotify() kWhatFlagsChanged  FLAG_CAN_PAUSE: 1  FLAG_CAN_SEEK_BACKWARD: 1 
02-28 17:38:06.461  3426 15233 V NuPlayer: NuPlayer::onSourceNotify Source::kWhatPrepared source: 0xe7d6dc40

I’ve noticed that ‘sound = null’ is being logged, which is kind of weird.
Thanks in advance.

With kind regards,

Jonah

Posts: 1

Participants: 1

Read full topic

Lazy loading from common folder

$
0
0

@stephaneHillerCGI wrote:

I have a repo with three folder : 2 ionic apps and a common module. The goal of this common module is to provide common information for the two ionic projects (the module contains providers, component, models, pages, …).

But when you try to lazy load a page from the module, it doesn’t work (“core.js:1350 ERROR Error: Uncaught (in promise): invalid link: MyPage”).

Is it possible that Ionic doesn’t “see” the IonicPage() annotation because this annotation isn’t in the src folder ? If true, is it possible to extends the watcher to another folder so Ionic can recognize the annotation ?

   ionic (Ionic CLI)  : 4.11.0 (C:\Users\stephane.hiller\AppData\Roaming\npm\node_modules\ionic)
   Ionic Framework    : ionic-angular 3.9.2
   @ionic/app-scripts : 3.1.0

System:

   NodeJS : v8.9.4 (C:\Program Files\nodejs\node.exe)
   npm    : 5.6.0
   OS     : Windows 7

ps: my current ionic version is 4.11, but it’s an Ionic v3 application.
ps 2 : I’ve open an issue on ionic github : https://github.com/ionic-team/ionic-v3/issues/983

Posts: 1

Participants: 1

Read full topic

Series of Ionic apps

$
0
0

@fpagano wrote:

I would like to publish a series of Ionic apps that share the same code and differ only for some resources (eg the icon and the background image) and the title. Each of these apps must contain an identifier to download the appropriate data from the Cloud. Is there a way to automate this process or do I have to manually modify the config.xml file, create certificates, deploy, etc.? Apps must be published on both Google Play and iTunes.

Posts: 1

Participants: 1

Read full topic

Can't change ion-input style from global.scss

$
0
0

@joe_scotto wrote:

Ionic v4 has been a nightmare for me being able to override styles. I find it quite confusing and overly complex to simply change the style of an input but that’s beside the point… The issue I’m currently having is that my css works fine when on the component .scss file but I wish to globally override all ion-input but it will only work from global.scss when I use !important

ion-input {
    background: rgba(var(--ion-color-light-rgb), 1);
    color: var(--ion-color-light-contrast);
    margin-bottom: 16px;
    height: 50px;
    border-radius: var(--radius);
    padding-left: 16px;
}

ion-input,
ion-button {
    max-width: var(--content-max-width) !important;
    margin: 0 auto 16px auto !important;
}

This code works perfectly fine on the individual page .scss files but once I put it in global.scss it no longer will work unless I use !important

Posts: 1

Participants: 1

Read full topic

Using native Camera plugin

$
0
0

@lstables wrote:

Hi all,

I’m using the native camera plugin on v3 of Ionic, all is working fine, but I wish to know if there’s a way to get the photo’s metadata, like the timestamp and location (if location service turned on) of when the photo was taken. If so how?

Posts: 1

Participants: 1

Read full topic

Ionic 4 - bug trying to skip login page if user is logged in

$
0
0

@dev-gilbert wrote:

I am basically trying to implement a logic that when the user is logged in, they should be taken immediately to the home page and skip the login page. Right now my code works, but there’s a delay, because the value of my BehaviorSubject is initialized as false and when I subscribe to it in my app.component.ts the initialization value of my BehaviorSubject is always false, then it changes to the last emitted value, which I change to true when the user logs in.

My problem is that due to the small delay, the login page first appears on the screen then it quickly changes to the home page.

Look at this screenshot:

TL;DR What can I do so when I subscribe to my BehaviorSubject I always get the last emitted value, ignoring its initial value?

Below some code for more info:

service.ts:

authenticationState = new BehaviorSubject(false);

constructor (...) {
    //Check if token is stored when the device is ready
    this.plt.ready().then(readySource => {
      this.checkToken();
    });
  }

  checkToken() {
    return this.storage.get(TOKEN_KEY).then(res => {
      if (res) {
        this.authenticationState.next(true);
      }
    });
  }

login() {
    return this.storage.set(TOKEN_KEY, "user123").then(() => {
      this.authenticationState.next(true);
    });
  }

app.component.ts:

constructor(...) { this.initializeApp() }

initializeApp() {
 console.log(
        "auth state current value is: " +
          this.authService.authenticationState.getValue()
      );
      this.authService.authenticationState.subscribe(state => {
        console.log("Auth state: " + state);
        if (state) {
          this.router.navigate(["home"]);
        } else {
          this.router.navigate(["login"]);
        }
      });
}

Posts: 1

Participants: 1

Read full topic


Ionic 4 - ion-input underline

$
0
0

@blondie63 wrote:

On my project Ionic 4 Angular 7 i’ve a setting page with this code:

<ion-content padding class="tab4-content">
  <ion-list>
    <ion-item>
      <ion-label>{{ 'VERSION' | translate }}:</ion-label>
      <ion-label class="aligned-right">{{ version }}</ion-label>
    </ion-item>
  </ion-list>
  <ion-list>
    <ion-item>
      <ion-label>{{ 'GPS' | translate }}</ion-label>
      <ion-toggle [disabled]="GPSshouldDisable" checked="false"></ion-toggle>
    </ion-item>
    <ion-item>
      <ion-label>{{ 'GPSE' | translate }}</ion-label>
      <ion-toggle [disabled]="GPSEshouldDisable" checked="false"></ion-toggle>
    </ion-item>  
  </ion-list>
</ion-content>

this the result:

How can i change settings described on screenshot ?
Thanks

Posts: 2

Participants: 2

Read full topic

QR scanner not woking at all

Getting error in build time Ionic react : WebpackError: ReferenceError: window is not defined

Ionic4 Geolocation android

$
0
0

@iscorobogaci wrote:

import { Geolocation } from '@ionic-native/geolocation/ngx';

...

constructor(private geolocation: Geolocation) {}

...

this.geolocation.getCurrentPosition().then((resp) => {
 // resp.coords.latitude
 // resp.coords.longitude
}).catch((error) => {
  console.log('Error getting location', error);
});

let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
 // data can be a set of coordinates, or an error (if an error occurred).
 // data.coords.latitude
 // data.coords.longitude
});

The above code from documentation works fine in browser, but doesn’t do anything in android device :frowning:
Permissions are all set up

        <config-file parent="/manifest" target="AndroidManifest.xml">
            <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
            <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
            <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
        </config-file>

any idea on this ?

Posts: 1

Participants: 1

Read full topic

Are there any Android simulators for ionic serve?

$
0
0

@fostack wrote:

Not looking to emulate a device. It is moreso for esthetics. I’m making ionic development videos and I would like the view to be rendered within an Android frame as I’m updating code.

Thank you.

Posts: 1

Participants: 1

Read full topic

Impossible to build the application

$
0
0

@mouafus wrote:

greet the community!
I’m the new guy: @mouafus
I’m here because I can’t build the apk for my project made under ionic 3.
When I try the command “cordova build android” I get an error I don’t understand anything about. I need your help please :tired_face:

#Steven
here is a screenshot of the error

Posts: 1

Participants: 1

Read full topic

"System UI has stopped"

$
0
0

@Tony90 wrote:

Hi guys!

I’m developing an app using ionic 4.
During the beta testing one of my user get “System UI has stopped” when try to open the app and he can unistall the app only from google play store.

He’s using Android 8 on Motorola Moto z (griffin).
For now It’s the only person that get this error but it’s a major issue!

For the sake of completeness i paste here the plugin used to build the app:

 "cordova": {
    "plugins": {
      "cordova-plugin-whitelist": {},
      "cordova-plugin-statusbar": {},
      "cordova-plugin-device": {},
      "cordova-plugin-splashscreen": {},
      "cordova-plugin-ionic-webview": {
        "ANDROID_SUPPORT_ANNOTATIONS_VERSION": "27.+"
      },
      "cordova-plugin-ionic-keyboard": {},
      "cordova-sqlite-storage": {}
    },
    "platforms": [
      "ios",
      "android"
    ]
  }

and the dependencies in package.json

 "dependencies": {
    "@angular/animations": "^7.2.6",
    "@angular/cdk": "^7.3.3",
    "@angular/common": "^7.2.2",
    "@angular/core": "^7.2.2",
    "@angular/forms": "^7.2.2",
    "@angular/http": "^7.2.2",
    "@angular/material": "^7.3.3",
    "@angular/platform-browser": "^7.2.2",
    "@angular/platform-browser-dynamic": "^7.2.2",
    "@angular/router": "^7.2.2",
    "@ionic-native/core": "^5.0.0",
    "@ionic-native/in-app-purchase": "^5.2.0",
    "@ionic-native/splash-screen": "^5.0.0",
    "@ionic-native/sqlite": "^5.0.0",
    "@ionic-native/sqlite-porter": "^5.0.0",
    "@ionic-native/status-bar": "^5.0.0",
    "@ionic/angular": "^4.0.0",
    "@ionic/storage": "^2.2.0",
    "color": "^3.1.0",
    "cordova-android": "7.1.4",
    "cordova-ios": "^4.5.5",
    "cordova-plugin-device": "^2.0.2",
    "cordova-plugin-extension": "1.5.4",
    "cordova-plugin-inapppurchase": "1.2.0",
    "cordova-plugin-ionic-keyboard": "^2.1.3",
    "cordova-plugin-ionic-webview": "^3.1.2",
    "cordova-plugin-splashscreen": "^5.0.2",
    "cordova-plugin-statusbar": "^2.4.2",
    "cordova-plugin-whitelist": "^1.3.3",
    "cordova-promise-polyfill": "0.0.2",
    "cordova-sqlite-storage": "^3.1.0",
    "core-js": "^2.5.4",
    "iphone": "0.0.1",
    "rxjs": "~6.3.3",
    "web-animations-js": "^2.3.1",
    "zone.js": "~0.8.29"
  },
  "devDependencies": {
    "@angular-devkit/architect": "~0.12.3",
    "@angular-devkit/build-angular": "~0.12.3",
    "@angular-devkit/core": "~7.2.3",
    "@angular-devkit/schematics": "~7.2.3",
    "@angular/cli": "~7.2.3",
    "@angular/compiler": "~7.2.2",
    "@angular/compiler-cli": "~7.2.2",
    "@angular/language-service": "~7.2.2",
    "@ionic/angular-toolkit": "~1.3.0",
    "@ionic/lab": "1.0.20",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~10.12.0",
    "ajv": "^6.9.1",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.1.4",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~8.0.0",
    "tslint": "~5.12.0",
    "typescript": "~3.1.6"
  },

I really don’t know where can be the problem.
Thank you for your help!

Tony

Posts: 1

Participants: 1

Read full topic


Ionic3 cordova woo-commerce android app freeze while opening product page

$
0
0

@Hatimjamali wrote:

problem in Ionic3 cordova wordpress woo-commerce android app, from home.html page when tapping on a product many time it open product page perfectly but some time it freeze while opening product page, can not go back.
same problem from grid.html page when tapping on a product many time it open product page perfectly but some time it freeze while opening product page, can not go back.
some time it freeze on tapping after 2-3 products, some time it freeze on tapping after 7-8 products , open below link for video (live demo of problem)

app is live on play store search Het Nigeria

below link for code

http://www.mediafire.com/file/4bmk3c3zqkg5poe/grid.html.txt/file

http://www.mediafire.com/file/xd69t7y6mlzl2as/grid.ts.txt/file

http://www.mediafire.com/file/vjfjttb9e6bkqv5/product.html.txt/file

http://www.mediafire.com/file/i4ae4lev1pvqo4a/product.ts.txt/file

Grid.html*************************************************

  <div class="filter">
    <ion-scroll scrollX="true" class="item filter">
      <ion-row nowrap>
        <ion-col col-auto no-padding>
          <button ion-button small round outline (click)="showCategory()">{{param.name || ('CATEGORIES' |
            translate)}}</button>
        </ion-col>
        <ion-col col-auto no-padding *ngFor="let x of attributes">
          <button ion-button small round outline (click)="showFilter(x)">
            {{x.name}}
            <span *ngIf="param.attribute_term && param.attribute==x.slug">&nbsp;•&nbsp;{{param.attribute_term.split(",").length}}</span>
          </button>
        </ion-col>
        <!--<ion-col col-auto no-padding>-->
        <!--<button ion-button small round outline (click)="showSort()">Sort</button>-->
        <!--</ion-col>-->
      </ion-row>
    </ion-scroll>
  </div>
</div>

{{ 'EMPTY' | translate}}

  <button class="fav" (click)="setFav(x)" ion-button clear icon-only>
    <ion-icon *ngIf="x.variations.length == 0" no-padding name="heart{{!wishlist.isFav(x) ? '-outline' : ''}}"></ion-icon>
  </button>
  <div text-left class="product-item" tappable (click)="goTo('ProductPage', x)">
    <div class="img" [ngStyle]="{'background-image': 'url(' + x.images[0].src +')'}">
      <ion-badge *ngIf="x.on_sale">{{x | discount}}</ion-badge>
    </div>
    <h5 [innerHTML]="x.name"></h5>
    <div class="price">
      <span class="disc" *ngIf="x.on_sale">{{x.regular_price | money}}</span>
      {{x.price | money}}
    </div>
    <ion-row no-padding class="reviews" *ngIf="x.rating_count">
      <ion-col col-auto no-padding>
        <ion-rating *ngIf="x.average_rating" item-start [numStars]="5" [readOnly]="true" [value]="x.average_rating">
        </ion-rating>
        <span *ngIf="x.rating_count">{{x.rating_count}}</span>
      </ion-col>
    </ion-row>
  </div>
  <ion-row class="remove">
    <ion-col>
      <ng-container *ngIf="x.in_stock || !x.manage_stock">
        <button tappable (click)="addToCart(x)" ion-button small block>{{ 'TO_CART' | translate}}</button>
      </ng-container>
      <ng-container *ngIf="!x.in_stock && x.manage_stock">
        <button tappable ion-button small block disabled>Out of Stock</button>
      </ng-container>
    </ion-col>
  </ion-row>
</ion-col>

Grid.ts******************************************************************

import { Component } from ‘@angular/core’;
import { StatusBar } from ‘@ionic-native/status-bar’;
import { Keyboard } from ‘@ionic-native/keyboard’;
import { IonicPage, NavController, Platform, AlertController, ModalController, NavParams, ActionSheetController } from ‘ionic-angular’;
import { WooCommerceProvider, CartProvider, ToastProvider, LoadingProvider, WishlistProvider } from ‘…/…/…/providers/providers’;
import { TranslateService } from ‘@ngx-translate/core’;

import { FormGroup, FormBuilder } from ‘@angular/forms’;

@IonicPage()
@Component({
selector: ‘page-product-grid’,
templateUrl: ‘grid.html’,
})
export class ProductGridPage {
private search : FormGroup;

showCancel: boolean;

param: any = {};

WooCommerce: any;
subcategory: any;
products: any = ;

attributes: any = ;
categories: any;
min: number;
max: number;

page: number;
more: boolean;

constructor(private statusBar: StatusBar, private cart: CartProvider, private platform: Platform, private keyboard: Keyboard, public toast: ToastProvider, private alert: AlertController, fb: FormBuilder, private translate: TranslateService, private loader: LoadingProvider, public navCtrl: NavController, public modal: ModalController, public navParams: NavParams, private woo: WooCommerceProvider, public wishlist: WishlistProvider, public actionSheetCtrl: ActionSheetController) {
this.page = 1;

console.log(this.navParams.data.params);

this.param.name =  this.navParams.data.params.name ? this.navParams.data.params.name.replace(/&amp;/g, '&') : '';
this.param.id = this.navParams.data.params.id;
this.param.search = this.navParams.data.params.search ? this.navParams.data.params.search.replace(/&amp;/g, '&') : '';
this.param.per_page = 10;

this.search = fb.group({
		name: this.param.name || this.param.search
});

this.woo.getSubCategories().then( val=> {
  this.categories = val;
});

if(this.param.id) this.loadSubCategory(this.param.id);

this.woo.getAttributes().then((tmp) => {
  for(let i in tmp){
    this.attributes[i] = tmp[i];
    this.woo.getAttributeTerms(tmp[i].id).then((val) => {
      if(val){
        for(let j in val){
          val[j].checked = false;
          this.attributes[i].options = val;
        }
      }
    })
  }
});

// this.param.min = this.min;
// this.param.max = this.max;
this.loadProducts(this.param);

// if(this.platform.is(‘cordova’))
// this.keyboard.show();
}

ionViewWillEnter(){
if (this.platform.is(‘cordova’))
this.statusBar.styleDefault();
}

loadSubCategory(id){
this.woo.getCategories(id).then( y=> {
this.subcategory = y;
});
}

loadProducts(x: any){

this.loader.present();
this.woo.getAllProducts(1, x.id, x.search, null, null, x.per_page, null, x.order, x.attribute, x.attribute_term).then((val) => {
  this.products = val;
  
  if (this.products.length == x.per_page)
    this.more = true;
  
  this.loader.dismiss();
}, (err) => {
  console.log(err)
  this.loader.dismiss();
});

}

loadMoreProducts(event){
this.page++;

this.woo.getAllProducts(this.page, this.param.id, this.param.search, null, null, this.param.per_page, null, this.param.order, this.param.attribute, this.param.attribute_term).then((val) => {
  let temp = val;
  event.complete();
  this.products = this.products.concat(temp);

  if (temp.length < this.param.per_page){
    this.more = false;
    event.enable(false);

    this.translate.get(['NOMORE']).subscribe( x=> {
      this.toast.show(x.NOMORE);
    });
  }
}, (err) => {
  console.log(err)
});

}

showSort() {
this.translate.get([‘SORT’, ‘NEWEST’, ‘OLDEST’, ‘CANCEL’]).subscribe( x=> {
this.actionSheetCtrl.create({
title: x.SORT,
buttons: [{
text: x.NEWEST,
handler: () => {
this.param.order = ‘desc’;
this.loadProducts(this.param);
}
},{
text: x.OLDEST,
handler: () => {
this.param.order = ‘asc’;
this.loadProducts(this.param);
}
},{
text: x.CANCEL,
role: ‘cancel’
}
]
}).present();
});
}

viewCart(){
this.modal.create(‘MiniCartPage’, {}, { cssClass: ‘inset-modal’ }).present();
}

addToCart(product: any){
this.translate.get([‘ADDED_TO_CART’]).subscribe( x=> {
this.cart.post(product);
this.toast.show(x.ADDED_TO_CART);
});
this.viewCart();
}

setFav(product: any){
this.translate.get([‘REMOVE_WISH’, ‘ADDED_WISH’]).subscribe( x=> {
let msg = product.isFav ? x.REMOVE_WISH : x.ADDED_WISH;
this.wishlist.post(product);
product.isFav = product.isFav ? false : true;
this.toast.show(msg);
});
}

showFilter(attribute: any){
this.loader.present();
let alert = this.alert.create();
alert.setTitle(attribute.name);
this.translate.get([‘FILTER_DESC’], {value: attribute.name}).subscribe( x=> {
alert.setSubTitle(x.FILTER_DESC);
});

for(let x in attribute.options){
  alert.addInput({
    type: 'checkbox',
    label: attribute.options[x].name,
    value: attribute.options[x].id,
    checked: this.param.attribute_term ? this.param.attribute_term.includes(attribute.options[x].id) : false
  });
}

this.translate.get(['CANCEL']).subscribe( x=> {
  alert.addButton(x.CANCEL);
});

alert.addButton({
  text: 'Ok',
  handler: (data: any) => {
    this.param.attribute = attribute.slug;
    this.param.attribute_term = data.join();  
    this.loadProducts(this.param);
  }
});

alert.present();
this.loader.dismiss();

}

showCategory(){
this.loader.present();
let alert = this.alert.create();
this.translate.get([‘CATEGORIES’, ‘CATEGORIES_DESC’]).subscribe( x=> {
alert.setTitle(x.CATEGORIES);
alert.setSubTitle(x.CATEGORIES_DESC);
});

for(let x in this.categories){
  alert.addInput({
    disabled: true,
    type: 'radio',
    label: this.categories[x].name.replace(/&amp;/g, '&')
  });
  for(let y in this.categories[x].child){
    alert.addInput({
      type: 'radio',
      label: this.categories[x].child[y].name.replace(/&amp;/g, '&')+' ('+this.categories[x].child[y].count+')',
      value: this.categories[x].child[y],
      checked: this.categories[x].child[y].id == this.param.id ? true : false
    });
  }
}

this.translate.get(['CANCEL']).subscribe( x=> {
  alert.addButton(x.CANCEL);
});

alert.addButton({
  text: 'Ok',
  handler: (data: any) => {
    this.param.id = data.id;
    this.param.name = data.name;
    this.loadSubCategory(this.param.id);
    this.loadProducts(this.param);
  }
});
alert.present();
this.loader.dismiss();

}

submit(){
this.param.search = this.search.value.name;
this.loadProducts(this.param);
}

reset(e){
this.param.search = ‘’;
this.search.reset();
}

backToRoot(){
this.navCtrl.pop();
}

goTo(page, params){
this.navCtrl.push(page, {params: params});
}

}

Product.html*****************************************************

    <ion-list-header mode="md" no-margin no-padding margin-left *ngIf="product.variations.length > 0">
      {{'VARIATION' | translate}}
    </ion-list-header>
    <ion-list mode="md" radio-group (ionChange)="setVariation($event)" padding-bottom no-margin margin-horizontal margin-bottom *ngIf="product.variations.length > 0">
      <ion-item mode="ios" *ngFor="let x of product.variations" no-padding>
          <ion-label>
            <span *ngFor="let y of x.attributes">
              {{y.name}}: {{y.option}}
            </span>
          </ion-label>
          <ion-radio mode="ios" value="{{x | json}}"></ion-radio>
      </ion-item>
    </ion-list>

    <ion-list mode="md" class="specs">
      <ion-list-header mode="md" no-margin no-padding margin-left>
        {{'SPECIFICATION' | translate}}
      </ion-list-header>
      <ion-item>
        <ion-grid no-padding>
            <ion-row no-padding>
                <ion-col col-4 no-padding>Category</ion-col>
                <ion-col col-8 no-padding>
                  <span *ngFor="let cat of product.categories">{{cat.name}}</span>
                </ion-col>
            </ion-row>
            <!--ion-row no-padding *ngIf="product.total_sales">
                <ion-col col-4 no-padding>Total Sales</ion-col>
                <ion-col col-8 no-padding>
                  {{product.total_sales}}
                </ion-col>
            </ion-row-->
            <ion-row no-padding *ngIf="product.sku">
                <ion-col col-4 no-padding>SKU</ion-col>
                <ion-col col-8 no-padding>
                  {{product.sku}}
                </ion-col>
            </ion-row>
            <ion-row no-padding *ngIf="product.in_stock">
                <ion-col col-4 no-padding>Stock</ion-col>
                <ion-col col-8 no-padding>
                  {{product.stock_quantity}}
                </ion-col>
            </ion-row>
            <ion-row no-padding *ngIf="product.weight">
                <ion-col col-4 no-padding>Weight</ion-col>
                <ion-col col-8 no-padding>
                  {{product.weight}}
                </ion-col>
            </ion-row>
            <ion-row no-padding *ngFor="let att of product.attributes">
                <ion-col col-4 no-padding>{{ att.name}}</ion-col>
                <ion-col col-8 no-padding *ngIf="!att.options">
                  {{att.option}}
                </ion-col>
                <ion-col col-8 no-padding *ngIf="att.options">
                  <span *ngFor="let option of att.options"> {{ option }}</span>
                </ion-col>
            </ion-row>
        </ion-grid>
      </ion-item>
  </ion-list>

    <ion-list mode="md" *ngIf="product.description">
      <ion-list-header mode="md" no-margin no-padding margin-left margin-top>
        {{'DESCRIPTION' | translate}}
      </ion-list-header>
      <ion-item mode="md">
        <div [innerHTML]="product.description"></div>
      </ion-item>
    </ion-list>

    <ion-list-header mode="md" no-margin no-padding margin-left *ngIf="product.rating_count > 0">
      {{'REVIEW' | translate}}
    </ion-list-header>
    <ion-list no-margin margin-horizontal padding-bottom *ngIf="product.rating_count > 0">
      <ion-item *ngFor="let x of product.reviews" no-padding>
        <ion-row no-padding>
            <ion-col col-4>
              <div>{{x.name}}</div>
              <div class="ago">{{x.date_created | moment:"ago" | lowercase}}</div>
              <ion-rating *ngIf="x.rating"
                [numStars]="5"
                [readOnly]="true"
                [value]="x.rating">
              </ion-rating>
            </ion-col>
            <ion-col col-8>
              {{x.review}}
            </ion-col>
        </ion-row>
      </ion-item>
    </ion-list>

    <div class="product-slide">
      <ion-list-header mode="md" no-margin no-padding margin-left margin-bottom>
        {{'RELATED' | translate}}
      </ion-list-header>

      <ion-slides margin-bottom spaceBetween="10" slidesPerView="2.5">
        <ion-slide *ngFor="let y of product.related">
          <button class="fav" tappable (click)="setFav(y)"  ion-button clear icon-only>
            <ion-icon *ngIf="y.variations.length == 0" no-padding name="heart{{!wishlist.isFav(y) ? '-outline' : ''}}"></ion-icon>
          </button>
          <div text-left class="product-item" tappable (click)="goTo('ProductPage', y)">
            <div class="img" [ngStyle]="{'background-image': 'url(' + y.images[0].src +')'}">
              <ion-badge *ngIf="y.on_sale">{{y | discount}}</ion-badge>
            </div>
            <h5 [innerHTML]="y.name"></h5>
            <div class="price" *ngIf="y.price">
                <span class="disc" *ngIf="y.on_sale">{{y.regular_price | money:app}}</span> 
                {{y.price | money:app}}
            </div>
            <ion-row no-padding class="reviews" *ngIf="y.rating_count">
              <ion-col col-auto no-padding>
                <ion-rating *ngIf="y.average_rating" item-start
                  [numStars]="5"
                  [readOnly]="true"
                  [value]="y.average_rating">
                </ion-rating>
                <span *ngIf="y.rating_count">{{y.rating_count}}</span>
              </ion-col>
            </ion-row>
          </div>
        </ion-slide>
      </ion-slides>
    </div>
  </div>

<ion-footer *ngIf=“product.price”>



<h5 *ngIf=“product.price”>
<span class=“disc” *ngIf=“product.on_sale”>{{product.regular_price | money:app}}
{{product.price | money:app}}

<ion-row no-padding class=“reviews” *ngIf=“product.rating_count”>

<ion-rating *ngIf=“product.average_rating” item-start
[numStars]=“5”
[readOnly]=“true”
[value]=“product.average_rating”>

<span *ngIf=“product.rating_count”>{{product.rating_count}}




<ng-container *ngIf=“product.in_stock || !product.manage_stock”>
<button ion-button block tappable (click)=“openModal(‘MiniCartPage’)”>{{‘TO_CART’ | translate}}

<ng-container *ngIf="!product.in_stock && product.manage_stock">
Out of Stock




Product.ts*******************************************************

import { Component } from ‘@angular/core’;
import { IonicPage, NavController, AlertController, Platform, ModalController, NavParams } from ‘ionic-angular’;
import { WishlistProvider, SettingsProvider, LoadingProvider, ToastProvider, WooCommerceProvider, HistoryProvider } from ‘…/…/providers/providers’;
import { SocialSharing } from ‘@ionic-native/social-sharing’;
import { TranslateService } from ‘@ngx-translate/core’;

@IonicPage()
@Component({
selector: ‘page-product’,
templateUrl: ‘product.html’,
})

export class ProductPage {
product: any = {
variations:
};

variations: any = ;
reviews: any = ;
related: any = ;
isSetVariation: boolean = false;

app: any;

constructor(private history: HistoryProvider, private settings: SettingsProvider, private alert: AlertController, private platform: Platform, private socialSharing: SocialSharing, private translate: TranslateService, private toast: ToastProvider, private wishlist: WishlistProvider, private navCtrl: NavController, private loader: LoadingProvider, private modal: ModalController, private navParam: NavParams, private woo: WooCommerceProvider) {
this.loader.present();

this.settings.load().then( (x)=> {
  this.app = x.settings;

  this.product = this.navParam.data.params;
  
  this.history.post(this.product);
  
  if(this.product.variations.length > 0){
    this.woo.getProductVariations(this.product.id).then( (val) => {
      this.product.variations = val;
    })
  }

  if(this.product.rating_count > 0){
    this.woo.getProductReviews(this.product.id).then( (val) => {
      this.product.reviews = val;
      this.loader.dismiss();
    })
  }

  this.product.related = this.woo.getProductRelated(this.product.related_ids);
  this.loader.dismiss();
})

}

ionViewWillEnter(){
}

setVariation(e){
let x = JSON.parse(e);
this.product.variation_id = x.id;
this.product.price = x.price;
this.product.regular_price = x.regular_price;
this.product.on_sale = x.on_sale;
this.product.in_stock = x.in_stock;
this.product.stock_quantity = x.stock_quantity;
this.product.attributes = x.attributes;
this.isSetVariation = true;
}

viewCart(){
this.modal.create(‘MiniCartPage’, {}, { cssClass: ‘inset-modal’ }).present();
}

openModal(pageName) {
if(this.product.variations.length > 0 && !this.isSetVariation){
this.translate.get([‘SELECT_VARIATION’]).subscribe( x=> {
this.toast.show(x.SELECT_VARIATION);
});
}else{
this.modal.create(pageName, {product: this.product}, { cssClass: ‘inset-modal’ }).present();
this.translate.get([‘ADDED_TO_CART’]).subscribe( x=> {
this.toast.show(x.ADDED_TO_CART);
});
}
}

setFav(product: any){
this.translate.get([‘REMOVE_WISH’, ‘ADDED_WISH’]).subscribe( x=> {
let msg = product.isFav ? x.REMOVE_WISH : x.ADDED_WISH;
this.wishlist.post(product);
product.isFav = product.isFav ? false : true;
this.toast.show(msg);
});
}

share(product: any){
// console.log(product);
if (!this.platform.is(‘cordova’)) {
this.translate.get([‘OK’, ‘ONLY_DEVICE’, ‘ONLY_DEVICE_DESC’]).subscribe( x=> {
this.alert.create({
title: x.ONLY_DEVICE,
message: x.ONLY_DEVICE_DESC,
buttons: [{
text: x.OK
}]
}).present();
return false;
});

}else{
  let img = [];
  for(let i in product.images)
    img.push(product.images[i].src);

  this.socialSharing.share(product.name, product.name, img, product.permalink).then((x) => {
    console.log(x);
    this.toast.show('Successfully shared');
  }).catch((err) => {
    console.log(err);
  });
}

}

goTo(page: string, params: any){
this.navCtrl.push(page, {params: params});
}

}

Posts: 1

Participants: 1

Read full topic

Sqlite mock with ionic v4

$
0
0

@Payamy wrote:

I have followed the following tutorial (https://medium.com/@tintin301/ionic-sqlite-storage-setting-up-for-browser-development-and-testing-67c0f17fc7af) in order to mock sqlite. My code is provided at https://github.com/Yavari/ionic-sqlite-mock, The mock is not recognized and I am getting the error bellow. I am new to both ionic and angular so I would appreciate if someone could help me with this issue.

ERROR TypeError: Cannot read property ‘then’ of undefined
at Tab1Page.push…/src/app/tab1/tab1.page.ts.Tab1Page.ngOnInit (tab1.page.ts:19)
at checkAndUpdateDirectiveInline (core.js:22098)
at checkAndUpdateNodeInline (core.js:23362)
at checkAndUpdateNode (core.js:23324)
at debugCheckAndUpdateNode (core.js:23958)
at debugCheckDirectivesFn (core.js:23918)
at Object.eval [as updateDirectives] (Tab1Page_Host.ngfactory.js? [sm]:1)
at Object.debugUpdateDirectives [as updateDirectives] (core.js:23910)
at checkAndUpdateView (core.js:23306)
at callViewAction (core.js:23547)

The create method in SQLiteMock is not called so it is as if my provide in the app.module.ts is not working

//https://github.com/Yavari/ionic-sqlite-mock/blob/master/src/app/app.module.ts
import { SQLite } from '@ionic-native/sqlite';
import { SQLitePorter } from '@ionic-native/sqlite-porter';
import { SQLiteMock, SQLitePorterMock } from './mocks/sqlite.mock';
@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: SQLite, useClass: SQLiteMock },
    { provide: SQLitePorter, useClass: SQLitePorterMock },
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

This is how I am trying to use it:

// https://github.com/Yavari/ionic-sqlite-mock/blob/master/src/app/tab1/tab1.page.ts
import { Component, OnInit } from '@angular/core';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';

@Component({
  selector: 'app-tab1',
  templateUrl: 'tab1.page.html',
  styleUrls: ['tab1.page.scss']
})
export class Tab1Page implements OnInit {

  constructor(private sqlite: SQLite) {

  }

  ngOnInit(): void {
    this.sqlite.create({
      name: 'data.db',
      location: 'default'
    }).then((db: SQLiteObject) => {
      db.executeSql('create table danceMoves(name VARCHAR(32))', [])
        .then(() => console.log('Executed SQL'))
        .catch(e => console.log(e));
    }).catch(e => console.log(e));
  }
}

This is my mock class that I have taken from the tutorial:

// https://github.com/Yavari/ionic-sqlite-mock/blob/master/src/app/mocks/sqlite.mock.ts
/*
  Implemented with the help of https://www.techiediaries.com/mocking-native-sqlite-plugin/
*/

import { SQLiteDatabaseConfig } from '@ionic-native/sqlite';

//SQL file is loaded via script tag in index.html --> <script src="assets/sql/sql.js"></script>
declare var SQL;

export class SQLiteObject {
    _objectInstance: any;

    constructor(_objectInstance: any) {
        this._objectInstance = _objectInstance;
    };

    executeSql(statement: string, params: any): Promise<any> {

        return new Promise((resolve, reject) => {
            try {
                console.log(statement)
                var st = this._objectInstance.prepare(statement, params);
                var rows: Array<any> = [];
                while (st.step()) {
                    var row = st.getAsObject();
                    rows.push(row);
                }
                var payload = {
                    rows: {
                        item: function (i) {
                            return rows[i];
                        },
                        length: rows.length
                    },
                    rowsAffected: this._objectInstance.getRowsModified() || 0,
                    insertId: this._objectInstance.insertId || void 0
                };
                //save database after each sql query

                var arr: ArrayBuffer = this._objectInstance.export();
                localStorage.setItem("database", String(arr));
                resolve(payload);
            } catch (e) {
                reject(e);
            }
        });
    };

    sqlBatch(statements: string[], params: any): Promise<any> {
        return new Promise((resolve, reject) => {
            try {
                var rows: Array<any> = [];
                for (let statement of statements) {
                    console.log(statement)
                    var st = this._objectInstance.prepare(statement, params);
                    while (st.step()) {
                        var row = st.getAsObject();
                        rows.push(row);
                    }
                }
                var payload = {
                    rows: {
                        item: function (i) {
                            return rows[i];
                        },
                        length: rows.length
                    },
                    rowsAffected: this._objectInstance.getRowsModified(),
                    insertId: this._objectInstance.insertId || void 0
                };
                //save database after each sql query

                var arr: ArrayBuffer = this._objectInstance.export();
                localStorage.setItem("database", String(arr));
                resolve(payload);
            } catch (e) {
                reject(e);
            }
        });
    };
}

/*
  Implemented using edited code from actual cordova plugin
*/
export class SQLitePorterMock {
    /**
     * Trims leading and trailing whitespace from a string
     * @param {string} str - untrimmed string
     * @returns {string} trimmed string
     */


    trimWhitespace(str) {
        return str.replace(/^\s+/, "").replace(/\s+$/, "");
    }

    importSqlToDb(db, sql, opts = {}) {
        try {
            const statementRegEx = /(?!\s|;|$)(?:[^;"']*(?:"(?:\\.|[^\\"])*"|'(?:\\.|[^\\'])*')?)*/g;
            var statements = sql
                .replace(/(?:\/\*(?:[\s\S]*?)\*\/)|(?:([\s;])+\/\/(?:.*)$)/gm, "") // strip out comments
                .match(statementRegEx);

            if (statements === null || (Array.isArray && !Array.isArray(statements))) statements = [];

            // Strip empty statements
            for (var i = 0; i < statements.length; i++) {
                if (!statements[i]) {
                    delete statements[i];
                }
            }
            return db.sqlBatch(statements)
        } catch (e) {
            console.error(e.message);
        }
    }
}

export class SQLiteMock {

    public create(config: SQLiteDatabaseConfig): Promise<SQLiteObject> {
        console.log("creating");
        var db;
        var storeddb = localStorage.getItem("database");

        if (storeddb) {
            var arr = storeddb.split(',');
            db = new SQL.Database(arr);
        }
        else {
            db = new SQL.Database();
        }

        return new Promise((resolve, reject) => {
            resolve(new SQLiteObject(db));
        });
    }
}

Posts: 1

Participants: 1

Read full topic

Ion-input jumps to next ion-input

$
0
0

@basti wrote:

I use ionic 4 latest version and have a grid with several ion-inputs in separated ion-rows.
Unfortunately when I add some content in one ion-input it jumps directly to the next and add the content there too.
It looks like a very strange behaviour to me.

0 was there, I added the 3:
capture_001_08032019_012605

or I typed “alles”:

capture_002_08032019_013048

Posts: 1

Participants: 1

Read full topic

Ion-datetime picker current date

$
0
0

@carlos271210 wrote:

Hi Guys quick question in here: This is my scenario :

  • Ionic v4

item.StartTime = null

  <ion-datetime  disabled="{{iProService.readonly}}" class="input-style"  picker-format="MM/DD/YYYY HH:mm" display-format="HH:mm" placeholder=" - Select - "
                [(ngModel)]="item.StartTime"  #dateStartTime  (ionChange)="updateProviderTime(item)">
              </ion-datetime>

I wanted to show today’s date on the picker , but I can’t use the ngmodel since I depend on that date in order to save the data. Any idea how to achieve this in here ?

Posts: 1

Participants: 1

Read full topic

Cordova plugins not working with Capacitor

$
0
0

@wekas wrote:

I’m not sure how to get Cordova plugins working with Capacitor.

I am following this example (https://ionicacademy.com/create-pdf-files-ionic-pdfmake/) but I am going to add some Capacitor plugins to it in order to use the camera.

Do the Cordova plugins below still work with Capacitor? I can’t get them to work at all. They work fine using cordova rather than Capacitor.
I have created project as folllows:

ionic start myApp
cd myApp
npm install @capacitor/core @capacitor/cli
npx cap init
npm install pdfmake @ionic-native/file-opener @ionic-native/file 
npm install cordova-plugin-file-opener2
npm install cordova-plugin-file

*Writes code that is in link*

create myApp/www dir
copied index.html to myApp/www dir
npx cap add android
npx cap open android (opens android studio)
ionic capacitor run android
run in emulator from android studio

OUTPUT in chrome debugger when saving and opening the pdf file:

Native: tried calling File.dataDirectory, but the File plugin is not installed.
capacitorConsole @ capacitor-runtime.js:81
Install the File plugin: 'ionic cordova plugin add cordova-plugin-file'
Native: tried accessing the File plugin but it's not installed.
Install the File plugin: 'ionic cordova plugin add cordova-plugin-file'

Error on line:
this.file.writeFile(this.file.dataDirectory, 'myletter.pdf', blob, { replace: true }).then(fileEntry => {

Posts: 1

Participants: 1

Read full topic

Viewing all 71530 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>