Showing posts with label ionic2. Show all posts
Showing posts with label ionic2. Show all posts

Wednesday, June 13, 2018

Error: Failed to transpile program - ionic2

Leave a Comment

I've been developing an app for 6 months now. I've never tested it on a device, always in browser, but it's gotten to the point where I want to test on my android phone.

So I do ionic cordova run android --device and I get an error:

Error: Failed to transpile program at BuildError.Error (native) at new BuildError (C:\xampp\htdocs\project x\projectx\node_modules\@ionic\app-scripts\dist\util\errors.js:16:28) at C:\xampp\htdocs\project x\projectx\node_modules\@ionic\app-scripts\dist\transpile.js:159:20 at transpileWorker (C:\xampp\htdocs\project x\projectx\node_modules\@ionic\app-scripts\dist\transpile.js:107:12) at Object.transpile (C:\xampp\htdocs\project x\projectx\node_modules\@ionic\app-scripts\dist\transpile.js:64:12) at C:\xampp\htdocs\project x\projectx\node_modules\@ionic\app-scripts\dist\build.js:109:82 [18:05:02] copy finished in 4.95 s

which I can't seem to fix.

I was curious if it was perhaps a problem with my machine, or phone, or something so I created a new ionic project by doing ionic start ionic-test and then simply running it again with ionic cordova run android --device, and this time it worked perfectly. It ran on my device.

So considering that, can I simply paste over my src files into the new project? or is there something else I can do to get this working? Any ideas/tips? Thanks!

Edit:

Here is a pastebin to the entire result of ionic cordova run android --device. https://pastebin.com/x1zX5U1e (note: there were about 200 code warnings from typescript but they were all very minor stuff)

And here is a pastebin for ionic info

https://pastebin.com/A628WpAW

Edit 2: I found the solution. I will be posting a detailed answer soon!

1 Answers

Answers 1

Okay, so I struggled with this for over a month, and I finally realized my issue was actually stupidly simple.

What I found was that even though my application compiled using ionic serve with the "warnings" it had, the application couldn't be built on a phone without removing those "warnings". I had something like over 40 warnings, and getting rid of them all took a few hours but afterwards ionic cordova run android --device worked perfectly.

So if you are having this problem: look at the typescript errors you have and fix them. Your problem should be fixed.

Read More

Saturday, June 2, 2018

Error: Failed to transpile program - ionic2

Leave a Comment

I've been developing an app for 6 months now. I've never tested it on a device, always in browser, but it's gotten to the point where I want to test on my android phone.

So I do ionic cordova run android --device and I get an error:

Error: Failed to transpile program at BuildError.Error (native) at new BuildError (C:\xampp\htdocs\project x\projectx\node_modules\@ionic\app-scripts\dist\util\errors.js:16:28) at C:\xampp\htdocs\project x\projectx\node_modules\@ionic\app-scripts\dist\transpile.js:159:20 at transpileWorker (C:\xampp\htdocs\project x\projectx\node_modules\@ionic\app-scripts\dist\transpile.js:107:12) at Object.transpile (C:\xampp\htdocs\project x\projectx\node_modules\@ionic\app-scripts\dist\transpile.js:64:12) at C:\xampp\htdocs\project x\projectx\node_modules\@ionic\app-scripts\dist\build.js:109:82 [18:05:02] copy finished in 4.95 s

which I can't seem to fix.

I was curious if it was perhaps a problem with my machine, or phone, or something so I created a new ionic project by doing ionic start ionic-test and then simply running it again with ionic cordova run android --device, and this time it worked perfectly. It ran on my device.

So considering that, can I simply paste over my src files into the new project? or is there something else I can do to get this working? Any ideas/tips? Thanks!

Edit:

Here is a pastebin to the entire result of ionic cordova run android --device. https://pastebin.com/x1zX5U1e (note: there were about 200 code warnings from typescript but they were all very minor stuff)

And here is a pastebin for ionic info

https://pastebin.com/A628WpAW

0 Answers

Read More

Tuesday, February 20, 2018

How to add slider for google map info card in ionic 3

Leave a Comment

i am very new to ionic framework. I want to add multiple markers along with the information card in the slider form just like the image attached with this . I have able to add multiple markers in the map but no idea how to add information slider which will activate the marker. corresponding to the slider. Can any please give me some hint on how to work with this.

My eventmap.ts file to show multiple markers

export class EventMapPage {     public userToken:any;     public userPostData = {"api_token":""};     public responseData:any;     public dataSet:any;        @ViewChild('map') mapRef:ElementRef;    constructor(...) {       this.getEvents().then(result=> {           this.responseData = result;           this.DisplayMap(this.responseData);       });    }       //Get all the available events     getEvents(){         const data = localStorage.getItem('userToken');         this.userPostData.api_token= data;         return this.authService.postData(this.userPostData,'events');     }      //Initializing the map     DisplayMap(data) { this.geolocation.getCurrentPosition().then((resp) => {    const location = new google.maps.LatLng(resp.coords.latitude,      resp.coords.longitude);    const options = {      center:location,      zoom:10,      mapTypeControl: false,      streetViewControl:false,    };      const map = new google.maps.Map(this.mapRef.nativeElement,options);      //Loop the markers        if(data != null){          for(var i=0; i<data.length; i++){            this.multipleMaker(parseFloat(data[i].lat),parseFloat(data[i].lon),map);          }        }     }).catch((error) => {       console.log('Error getting location', error);     });    }    //Marker function  multipleMaker(lat,lng,map) {     return new google.maps.Marker({         position:{lat:lat,lng:lng},         map:map     }); }   } 

enter image description here

1 Answers

Answers 1

After some trail an error , research on google, i finally figured it out .

The solution to this that i come up with is as follows

in map.html

<ion-content >   <div #map id="map">   </div>    <div  class="slider-wraper">     <ion-slides slidesPerView="1" (ionSlideDidChange)="slideChanged()">       <ion-slide *ngFor="let item of responseData?.weekEvents">         <ion-card tappable (click)="viewDetail(item.id)">           <div class="event-image-holder search-list">             <img src="http://localhost:8000/{{item.photo_url}}"/>           </div>           <ion-card-content>             <div class="event-info">               <div class="event-descp">                 <h2>{{item.title}}</h2>                 <p>                   {{item.club.name}}                 </p>                 <p>                   <strong>{{item.attendees.length}} are going</strong>                 </p>               </div>             </div>           </ion-card-content>         </ion-card>       </ion-slide>     </ion-slides>   </div> </ion-content> 

in map.ts

First import slider

import { Slides } from 'ionic-angular'; 

Then inside class get the reference of the slider

@ViewChild(Slides) slides: Slides; 

Then add this methord

slideChanged() {     let currentIndex = this.slides.getActiveIndex();     let currentEvent  =this.responseData.weekEvents[currentIndex];     this.map.setCenter({lat: parseFloat(currentEvent.lat),lng:parseFloat(currentEvent.lon)}); } 

This will make the marker of current slider as the center of the map

Only thing now left to do is clicking on marker should make the slider active. I will update it here once its done. :))

Read More

Sunday, January 14, 2018

Unable to show dialog | Facebook Appinvites | IONIC 2

Leave a Comment

I am working with Facebook AppInvites.

I need to send direct message/invitation from my app to my facebook friends.

I am trying this code -

  this.facebook.appInvite(                 {                     url: "myapp://invite_from_fb?referral=123456789",                     picture: ""                 }             ); 

Error -

ERROR Error: Uncaught (in promise): Cannot show dialog

enter image description here

1 Answers

Answers 1

this feature is not available anymore and will be depcreated in a few weeks, so better search for another solution.

https://developers.facebook.com/docs/app-invites/android

I am sorry for having no better answer for you. It seems like facebook do not want to provide app invitations anymore.

Read More

Saturday, November 18, 2017

Unable perform google plus sign in ios using ionic 2

Leave a Comment

Hi i am applying social login scenario in my ionic app where i applied google sign option and it is working perfectly with android and when comming to the ios im getting the below error

the api key and bundle id everything are set and working perfect

ios google plus error

1 Answers

Answers 1

You have to follow the below steps as configuration for google login through IOS

  1. Go to https://developers.google.com/mobile/add?platform=ios&cntapi=signin for IOS registration
  2. Enter IOS bundle Id from widget Id in config.xml of the project
  3. Enable Google sign In and generate configuration file
  4. Copy the reverse client Id from downloaded file
  5. Install the plugin with reverse client Id instead of webclient Id which we used for Android
  6. run cordova plugin add cordova-plugin-googleplus --save --variable REVERSED_CLIENT_ID="myreversedclientid" We can find the reverse client Id in Google developer console also credentials->iOS URL schema is the reverse client Id

Extract from Plugin documentation

To get your iOS REVERSED_CLIENT_ID, generate a configuration file here. This GoogleService-Info.plist file contains the REVERSED_CLIENT_ID you'll need during installation. This value is only needed for iOS.

The REVERSED_CLIENT_ID is also known as the "iOS URL Scheme" on the Developer's Console.

Login on iOS takes the user to a SafariViewController through the Google SDK, instead of the separate Safari browser.

IMPORTANT:

  1. Please note that myreversedclientid is a place holder for the reversed clientId you find in your iOS configuration file. Do not surround this value with quotes. (iOS only Applications)

  2. If you are building a hybrid application (iOS and Android), or an Android application, you have to replace myreversedclientid with the reverse value of Client ID in your Release credential generated on step 3, on Google Developer's Console, this will be: "com.googleusercontent.apps.uniqueId", without quotes.

Read More

Sunday, October 22, 2017

Accessing Style of Ionic 2 DOM Elements

Leave a Comment

I'm trying to access the DOM elements of one of my pages with the following:

 ionViewDidEnter() {      this.platform.ready().then(() => {        let elm = <HTMLElement>document.querySelector("ion-navbar.toolbar.toolbar-ios.statusbar-padding");       console.log(elm.style);     })  } 

However, it appears this element has no style - I have tried various combinations to access it but no luck.

Specifically, I'm looking for the height of the ion-navbar. Is this possible?

3 Answers

Answers 1

You can get the actual height of an element with element.offsetHeight.

As for the style property, it will give you only the attributes defined in the element's inline style attribute (e.g. <div style="height: 20px;">...</div>), not the ones applied by the CSS using selector rules. See this MDN article for more details.

Answers 2

This is my workaround for that.

let tabs = document.querySelectorAll('.show-tabbar');       if (tabs !== null) {           Object.keys(tabs).map((key) => {               tabs[key].style.transform = 'translateY(56px)';           });   } 

Answers 3

I always have found it terribly useful to simply use ionic serve inspect the element in chrome and easily see the style for the given device.

To access the DOM element in angular I have used the #id route. The following snippet was used to verify the appropriate class was applied by ionic.

html- home.html

<ion-spinner #testspinner name="crescent" paused="{{isPaused}}"></ion-spinner> 

ts- home.ts

import {Component} from '@angular/core'; import {ViewChild} from '@angular/core';   @Component({   selector: 'page-home',   templateUrl: 'home.html' }) export class HomePage {   isPaused: boolean;   @ViewChild('testspinner') testspinner;    constructor() {     this.isPaused = false; // set to true will cause to never have animation state running.   }     containsPausedClass(list: string[]) {     return (list.indexOf('spinner-paused') != -1);   }    ngAfterViewInit() {     // if the spinner is allows to load without 'spinner-paused' then safari will work.     setTimeout(() => {       this.isPaused = true;     }, 0);     console.log('test spinner is paused ',       this.containsPausedClass(this.testspinner._elementRef.nativeElement.classList.value));    }    togglePause() {     this.isPaused = !this.isPaused;      setTimeout(() => {        console.log('test spinner is paused ',         this.containsPausedClass(this.testspinner._elementRef.nativeElement.classList.value));     }, 100);   }  } 
Read More

Friday, August 11, 2017

Ionic 2 cannot find module 'dgram'

Leave a Comment

I have installed a template Ionic 2 application and want to add the NPM package bonjour

After installing and including the package in my component like this:

var Bonjour = require('bonjour'); var bonjour = new Bonjour(); 

The application won't run stating 'cannot find module dgram'

The application has both the bonjour package and bonjour types installed.

The problem

The application can't find the module dgram which is located in the @types/node file. The project is running TS 2.4.2 and should not need any references to the @types, this should be picked up automatically.

What have I tried

I tried including the @types folder anyway in multiple ways, by setting typeroots or types in the ts.config.json file. This didn't change anything.

I tried specifying types :

"types": ["node", "bonjour"] 

I tried reinstalling all node modules and clearing the cache

I tried including a reference path in my component above the require statement:

/// <reference path="node_modules/@types/node/index.d.ts" />  var Bonjour = require('bonjour'); var bonjour = new Bonjour(); 

This all did not help. Any ideas on how to make my application load this module properly?

2 Answers

Answers 1

The package Bonjour has a DatagramPlugin which require dgram to function properly. In Ionic 2 this package is not available. The solution is to use the Native Zeroconf package as an alternative.

Answers 2

dgram library is included with node.js since v0.1.99 as seen here.

You will always have dgram defined as long as you use a node version post v0.1.99. Your problem is only with Typescript types.


Make sure you are installing node types with npm i --save-dev @types/node and that you are including the es6 lib in your tsconfig.json file.

If the previous step does not work add this on the top: import * as dgram from "dgram";

If nothing works you can copy the module definition from here export it yourself.


Extra tip: If you do not trust your tsconfig.json for some reason pass the lib and types argument directly in the tsc command such as: tsc --lib es6 --types node -p .

Read More

Saturday, June 3, 2017

Android video plays on iOS device but not on Android device

Leave a Comment

I have a strange situation where:

  • Android recorded video plays on an iPhone but not on an Android device
  • iPhone recorded videos play on both iPhones and Android devices

The HTML I use is:

          <video controls="controls">             <source type="video/quicktime" [src]="sanitizer.bypassSecurityTrustResourceUrl(step.attachment)">             <source type="video/mp4" [src]="sanitizer.bypassSecurityTrustResourceUrl(step.attachment)">           </video> 

The step.attachment is a base64 file.

My App is built with ionic 2

1 Answers

Answers 1

This should be a comment but I don't have enough rep to comment.

Perhaps explicitly determine the OS of the phone first and only define the video source for that OS.

For instance, the following algorithm:

if OS == Android, video controls source type="video/mp4"

else if OS == iOS, video controls source type="video/quicktime"

Although I don't see why what you have should work, hopefully you loose nothing trying this.

Read More

Thursday, April 6, 2017

Not been able to set focus to my <ion-input> as i enter the page

Leave a Comment

I want focus to be set on my <ion-input> as I enter the page

This is my typescript code:

import { Component, Input, ViewChild,ElementRef,Renderer } from '@angular/core'; import { NavController, PopoverController, NavParams, ViewController, ModalController } from 'ionic-angular';  @Component({   selector: 'page-comments',   templateUrl: 'comments.html' }) export class CommentsParentPage {     @ViewChild('input') myInput;      constructor(public navCtrl: NavController,private renderer: Renderer,                  private elementRef: ElementRef, public modalCtrl: ModalController) {     }      ionViewLoaded() {         setTimeout(() => {           let element = this.elementRef.nativeElement.querySelector('input');           this.renderer.invokeElementMethod(element, 'focus', []);        },150);     }  } 

And this is what i have done with my html file:

 <ion-item>       <ion-input set-focuser type="text" placeholder="Write Your Comments" [(ngModel)]="addComment"></ion-input>      </ion-item> 

Whenever I enter this page of my application, I would like the keyboard to be opened and focus to be set on ion-input

My config.xml includes:

<preference name="KeyboardDisplayRequiresUserAction" value="false" /> 

package.json

 {   "name": "sample app",   "author": "",   "homepage": "http://ionicframework.com/",   "private": true,   "scripts": {     "clean": "ionic-app-scripts clean",     "build": "ionic-app-scripts build",     "ionic:build": "ionic-app-scripts build",     "ionic:serve": "ionic-app-scripts serve"   },   "dependencies": {     "@angular/common": "2.2.1",     "@angular/compiler": "2.2.1",     "@angular/compiler-cli": "2.2.1",     "@angular/core": "2.2.1",     "@angular/forms": "2.2.1",     "@angular/http": "2.2.1",     "@angular/platform-browser": "2.2.1",     "@angular/platform-browser-dynamic": "2.2.1",     "@angular/platform-server": "2.2.1",     "@ionic-native/core": "^3.4.4",     "@ionic-native/keyboard": "^3.4.4",     "@ionic/cloud-angular": "^0.10.0",     "@ionic/storage": "1.1.7",     "angular2-moment": "^1.1.0",     "google-libphonenumber": "^2.0.14",     "ionic-angular": "2.0.0-rc.4",     "ionic-gallery-modal": "0.0.7",     "ionic-native": "2.2.11",     "ionicons": "3.0.0",     "rxjs": "5.0.0-beta.12",     "zone.js": "0.6.26"   },   "devDependencies": {     "@ionic/app-scripts": "1.0.0",     "typescript": "2.0.9"   },   "cordovaPlugins": [     "ionic-plugin-keyboard",     "cordova-plugin-whitelist",     "cordova-plugin-console",     "cordova-plugin-statusbar",     "cordova-plugin-device",     "cordova-plugin-splashscreen",     "cordova-sqlite-storage",     "cordova-plugin-x-toast",     "cordova-plugin-camera",     "cordova-plugin-compat",     "cordova-plugin-image-picker",     "cordova.plugins.diagnostic",     {       "id": "phonegap-plugin-push",       "locator": "phonegap-plugin-push",       "variables": {         "SENDER_ID": "461076790064"       }     },     "cordova-plugin-contacts",     "ionic-plugin-deploy",     "cordova-plugin-x-socialsharing",     {       "locator": "https://github.com/napolitano/cordova-plugin-intent",       "id": "com.napolitano.cordova.plugin.intent"     },     "cordova-plugin-screen-orientation",     "cordova-plugin-file",     "cordova-plugin-file-transfer"   ],   "cordovaPlatforms": [     {       "platform": "android",       "version": "",       "locator": "android"     }   ],   "description": "ionic2: An Ionic project" } 

4 Answers

Answers 1

use ngAfterViewChecked:

See plnkr here

import { Component, Input, ViewChild,ElementRef,Renderer, AfterViewChecked,ChangeDetectorRef  } from '@angular/core'; import { NavController, PopoverController, NavParams, ViewController, ModalController } from 'ionic-angular';  @Component({   selector: 'page-comments',   templateUrl: 'comments.html' })  export class CommentsParentPage implements AfterViewChecked { @ViewChild('input') myInput;  needsFocus: boolean;  constructor(public navCtrl: NavController,private renderer: Renderer,              private elementRef: ElementRef, public modalCtrl: ModalController,              private _changeDetectionRef: ChangeDetectorRef) { }  ionViewDidEnter() {     this.needsFocus = true; }  public ngAfterViewChecked(): void {     if (this.needsFocus) {         this.needsFocus = false;         this.myInput.setFocus();         this._changeDetectionRef.detectChanges();     } } 

Answers 2

You can do it using Directive as shown below.Hope code is self-explanatory.If you have any issue please comment below.

Play with Git Repo code.

You can View this on Ionic View: Id = F5F367AE

Note: Just tap My Page.

enter image description here

set-focuser.ts

import { Directive, Renderer, ElementRef } from '@angular/core'; import { Keyboard } from '@ionic-native/keyboard';  @Directive({   selector: '[set-focuser]' // Attribute selector }) export class SetFocuser {    constructor(private renderer: Renderer, private elementRef: ElementRef, public keyboard: Keyboard) {   }    ngAfterViewInit() {     const element = this.elementRef.nativeElement.querySelector('input');     // to delay      setTimeout(() => {       this.renderer.invokeElementMethod(element, 'focus', []);       this.keyboard.show();     }, 500);   }  } 

.html

 <ion-input set-focuser type="text"></ion-input> 

app.module.ts

import { SetFocuser } from "../components/set-focuser/set-focuser";  @NgModule({   declarations: [      SetFocuser,   ], 

Issues on your package.json

  1. You have to remove "ionic-native": "2.2.11", module.

  2. Use "@ionic/app-scripts": "1.1.4", instead of "@ionic/app-scripts": "1.0.0",

  3. After the above changes run npm i

This is the official package.json file.

Answers 3

If you want to control your keyboard programatically, then add the Ionic keyboard plugin

If you just want autofocus, add this Angular 2 dependency.

You could try binding one action to trigger the other (focus => open keyboard).

Try also testing your code on your desktop to see how autofocus reacts.

Answers 4

You can try simple method.

 <div ng-init="getfocus()">    <ion-input id="myAnchor" type="text" placeholder="Write Your Comments"/> </div> 

In js file call a function with ng-init

function getfocus() {    document.getElementById("myAnchor").focus(); } 

Hope this code will help you.if you get any error please comment.

Read More

Monday, April 3, 2017

Shopping List not listing/saving more than 1 recipe

Leave a Comment

My Aim is

  1. Create a shopping list which is pulling recipes from an API.
  2. Take ingredients from one page to another.
  3. Page to refresh/load data when more than 1 is added.

The issue I am having is

  1. Only 1 set of ingredients load
  2. The clear function will not allow anymore to be added.

Recipe Page

// Loading Recipes  /////////////////////////////////////////////////////////////////////  loadDetails1(id){     this.apiAuthentication.loadDetails(id)     .then(data => {         this.api = data;     }); }  // Add to Shopping List  /////////////////////////////////////////////////////////////////////   submit(api) {      let toast = this.toastCtrl.create({       message: 'Added to shopping list',       duration: 1000     });      console.log(this.api);      this.storage.get('myData').then((api) => {          // add one igredient to the ingredientLines object         // if it's still a string use JSON.parse() on it         this.storage.set('myData', api).then(result =>{             toast.present();             console.log(api);         });      });  } 

HTML

<h1 (click)="submit(api?.ingredientLines)">Add to shopping list</h1>  <ul>     <li *ngFor="let item of api?.ingredientLines"><span>{{item}}</span></li> </ul> 

Shopping List Page

getData() {   this.storage.get('myData').then((data => {       this.api = data;       console.log(data);        setInterval(() => {         console.log(data);       },5000);   })); } 

HTML

<ion-content padding>     <ion-card>         <ion-card-header>             {{api?.name}}         </ion-card-header>          <ion-list>             <ion-item>                 <ul>                     <li *ngFor="let item of api?.ingredientLines">                         <ion-label>{{item}}</ion-label>                         <ion-checkbox></ion-checkbox>                     </li>                 </ul>             </ion-item>         </ion-list>         <button ion-button block full color="danger" (click)="clear(item)">Remove</button>     </ion-card> </ion-content> 

Shopping list page looks like enter image description here

Error shown in visual is https://www.youtube.com/watch?v=BDS_XTdw2S0 You can see that when I add an item to the shopping list it does not update until i close the app and restart it. Also there is only ever 1 item.

1 Answers

Answers 1

You're overwriting your storage that's why only 1 appears.

It should look like this, try to use types and promises

public submit(ingredientLines: any) {  let toast = this.toastCtrl.create({     message: 'Added to shopping list',     duration: 1000 });  this.storage.get('myData').then((ingredientLines) => {      console.log(ingredientLines);      // add one igredient to the ingredientLines object     // if it's still a string use JSON.parse() on it     this.storage.set('myData', ingredientLines).then(result =>{         toast.present();     });  });  } 

So

  1. Get the data from storage

  2. Apply new item to data

  3. Set new data to storage

Read More

Sunday, April 2, 2017

Linking to external URL with appended tracking code in Ionic 2

Leave a Comment

I wish to have a unique http link to an external URL, pulled from my JSON data, from within the detail pages of my app.

I have installed the inappbrowser plugin that currently works with a static url going to apple.com. However, I wish to use a product specific link url from my JSON data. Here is the JSON data, it is the "aw_deep_link" I wish to use.

How can I link to an external URL pulled from an Angular expression using my Buy Button on the detail page and then append some Google Analytics tracking code to the end of the URL?

Here is the Google Tracking Code I want to append:

?utm_source=app&utm_medium=android 

Here is the Plunker currently working with a static url on the detail pages.

DETAIL.TS

openUrl() {          this.platform.ready().then(() => {             let browser = new InAppBrowser("http://www.apple.com",'_blank');             // let browser = new InAppBrowser("www.apple.com$?utm_source=app&utm_medium=android",'_blank');             // let browser = new InAppBrowser("{data.aw_deep_link}",'_blank');           }); } 

DETAIL.HTML

<button (click)="openUrl()" ion-item>Buy Now</button> 

Here is a similar concept used for Twitter pages in the Ionic Conference App

https://github.com/driftyco/ionic-conference-app/blob/master/src/pages/speaker-list/speaker-list.html

1 Answers

Answers 1

You weren't taking a url param in openUrl function.

<button (click)="openUrl(data.aw_deep_link)" ion-item>Buy Now</button>  openUrl(url) {     this.platform.ready().then(() => {         let browser = new InAppBrowser(`${url}?utm_source=app&utm_medium=android`,'_blank');         }); } 
Read More

Displaying Youtube within an Ionic 2 app

Leave a Comment

I am trying to display Youtube videos within an Ionic 2 application, with the URLs pulled in from a JSON data feed.

Individual videos can be displayed when the Youtube url is set in the constructor on the detail page, but I need the detail page to display videos for each of the videos in the JSON feed.

Here is how an individual Youtube video is able to display in Ionic 2 within detail.ts and detail.html:

1

import {SafeResourceUrl, DomSanitizer} from '@angular/platform-browser'; 

2

videoUrl: SafeResourceUrl;  constructor(private domSanitizer: DomSanitizer, public navCtrl: NavController) { this.videoUrl = this.domSanitizer.bypassSecurityTrustResourceUrl('https://www.youtube.com/embed/DuwXCFyo4-w') } 

3

<iframe width="100%" height="315" [src]="data.youtube" frameborder="0" allowfullscreen></iframe> 

ios tweak

<allow-navigation href="https://*youtube.com/*"/> 

What I need is some code tweaking in detail.ts to allow any Youtube url?

Here is the Youtube displayed in a Plunker on the detail page http://plnkr.co/edit/Ar2whVFCmBAbE7fxA3nf?p=preview

enter image description here

One solution I have seen is below, but can't seem to get it working:

transform(videoId: string): SafeResourceUrl { return this.domSanitizer.bypassSecurityTrustResourceUrl( https://www.youtube.com/embed/${videoId}); } 

1 Answers

Answers 1

You are doing it wrong. You shouldn't be using embedded youtube frames on your ionic app.

You must use the Ionic Youtube Plugin

To install it, go to your Ionic project in the command line:

ionic plugin add https://github.com/Glitchbone/CordovaYoutubeVideoPlayer.git npm install --save @ionic-native/youtube-video-player 

Basic Usage:

import { YoutubeVideoPlayer } from '@ionic-native/youtube-video-player';  constructor(private youtube: YoutubeVideoPlayer) { }  this.youtube.openVideo('myvideoid'); 

Of course 'myvideoid' is your youtube video ID passed as a string.

Read More

Wednesday, March 29, 2017

Ionic 2 floating ion-labels issue

Leave a Comment

I'm having an issue with some of the floating labels I'm using, not all of them, which makes it even stranger. As far as I can see my ion-items are written exactly the same. Here are some pictures to show you the issue. I'm not sure whether this is a bug in Ionic 2 or I'm doing something wrong. If there's anything unclear or you need more code, feel free to ask.

As you can see, the description and photo/video label are already acting like they should when they're in focus(they're not) but it's not displaying the highlights. problem

Here is an image where I put it in focus and then out of focus again. Once I do that it works correctly. enter image description here

Here is the html I wrote.

    <ion-content padding>      <form [formGroup]="complaint" (ngSubmit)="send()">     <ion-item>       <ion-label floating>Description*</ion-label>       <ion-textarea [(ngModel)]="description" type="text" formControlName="description"></ion-textarea>     </ion-item>     <ion-item>       <ion-label floating>Number of completed tests*</ion-label>       <ion-input [(ngModel)]="nrTests" type="number" formControlName="nrTests"></ion-input>     </ion-item>     <ion-item>       <ion-label floating>Photo/Video</ion-label>       <ion-input [(ngModel)]="media" formControlName="media"></ion-input>     </ion-item>     <button ion-button type="submit" [disabled]="!complaint.valid">Send</button>    </form> </ion-content> 

2 Answers

Answers 1

Remove floating and then try. I think this will resolve your issue.

Answers 2

Use stacked attribute to the ionic label and use the ion-item with in the ion-list.

Read More

Thursday, March 16, 2017

Ionic 2 SQLite Native as a Service

Leave a Comment

Anyone had success creating a service out of the SQLite ionic-native?

So one could end up with something like addItem(param), editItem(param), which calls the respective service function to handle the task?

With Storage and SqlStorage, I could do something like this:

import {Injectable} from '@angular/core'; import { Storage, SqlStorage } from 'ionic-angular';  @Injectable() export class CategoryService {        constructor() {      this.storage = new Storage(SqlStorage);      this.storage.query('CREATE TABLE IF NOT EXISTS category (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, type TEXT)');   }    saveCategory(data) {     let sql = 'INSERT INTO category (name, type) VALUES (?, ?)';     return this.storage.query(sql, [data.name, data.type]);   } } 

I've been reading the docs about using the SQLite in Ionic, and I'm not understanding how to do something along the lines of the above, Doc: https://ionicframework.com/docs/v2/native/sqlite/

How do you do it?

1 Answers

Answers 1

Not sure what the problem is.. here is how i use it

import { Injectable } from '@angular/core'; import { SQLite } from 'ionic-native';  @Injectable() export class DBService {      private db: SQLite;      constructor() {         this.db = null;     };      public open() {         if (window.sqlitePlugin) {             this.db = new SQLite();         } else { //handle in desktop if needed }     };  }  // other methods 
Read More

get high quality facebook profile picture with cordova plugin

Leave a Comment

I'm developing ionic 2 app. I'm trying to get high quality image and then resize it to avatar photo.

My code:

 _FBUserProfile() {  return new Promise((resolve, reject) => {   Facebook.api('me?fields=id,name,email,first_name,last_name,picture.width(600).height(600).as(picture_small),picture.width(360).height(360).as(picture_large)', [])     .then((profileData) => {       console.log(JSON.stringify(profileData));       return resolve(profileData);     }, (err) => {       console.log(JSON.stringify(err));       return reject(err);     }); }); 

}

But, the photo isn't good quality, since I guess I did something wrong with the resize in this line:

picture.width(600).height(600).as(picture_small),picture.width(360).height(360).as(picture_large)', []) 

How can I get good quality of the photo?

2 Answers

Answers 1

If you want to get the public profile picture of the user and you know the user id from the api call then use this url for picture

profileData.picture="https://graph.facebook.com/"+profileData.id+"/picture?width=1024&height=1024"; 

Answers 2

You've got a couple of solutions, like using type large

id,name,email,first_name,last_name,picture.type(large) 

As explained here: https://developers.facebook.com/docs/graph-api/reference/user/picture/

Read More

Wednesday, March 8, 2017

Ionic 2 build dev failed: Maximum call stack size exceeded

Leave a Comment

I cant build my ionic 2 App. Serving works after changing a file.

On ionic serve, I get the following error message:

[07:36:10]  ionic-app-scripts 1.0.0  [07:36:10]  watch started ...  [07:36:10]  build dev started ...  [07:36:10]  clean started ...  [07:36:10]  clean finished in 1 ms  [07:36:10]  copy started ...  [07:36:10]  transpile started ...  [07:36:15]  build dev failed: Maximum call stack size exceeded  [07:36:15]  dev server running: http://localhost:8100/  

Then when I change a *.ts file the app is built and can be used

[07:37:32]  build started ...  [07:37:32]  transpile started ...  [07:37:39]  build finished in 6.81 s  

When I run ionic build the following error message is displayed:

[07:40:40]  transpile started ...  [07:40:44]  build dev failed: Maximum call stack size exceeded  [07:40:44]  ionic-app-script task: "build"  [07:40:44]  RangeError: Maximum call stack size exceeded  RangeError: Maximum call stack size exceeded     at Object.binarySearch (/Users/huli/Documents/leseschlauapp/node_modules/typescript/lib/typescript.js:1327:26)     at computeLineAndCharacterOfPosition (/Users/huli/Documents/leseschlauapp/node_modules/typescript/lib/typescript.js:4070:29)     at Object.getLineAndCharacterOfPosition (/Users/huli/Documents/leseschlauapp/node_modules/typescript/lib/typescript.js:4089:16)     at emitPos (*/node_modules/typescript/lib/typescript.js:35556:36)     at emitStart (*/node_modules/typescript/lib/typescript.js:35598:13)     at emitNodeWithSourceMap (*/node_modules/typescript/lib/typescript.js:44266:21)     at emitNodeConsideringCommentsOption (*/node_modules/typescript/lib/typescript.js:44258:21)     at emit (*/node_modules/typescript/lib/typescript.js:44240:17)     at emitPropertyAccess (*/node_modules/typescript/lib/typescript.js:39200:17)     at emitJavaScriptWorker (*/node_modules/typescript/lib/typescript.js:44393:32)  npm ERR! Darwin 16.1.0 npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run" "ionic:build" "--" npm ERR! node v7.4.0 npm ERR! npm  v4.0.5 npm ERR! code ELIFECYCLE npm ERR! ionic-hello-world@ ionic:build: `ionic-app-scripts build` npm ERR! Exit status 1 

Here is my package.json if this might help

{   "name": "ionic-hello-world",   "author": "Ionic Framework",   "homepage": "http://ionicframework.com/",   "private": true,   "scripts": {     "ionic:build": "ionic-app-scripts build",     "ionic:serve": "ionic-app-scripts serve"   },   "dependencies": {     "@angular/common": "2.2.1",     "@angular/compiler": "2.2.1",     "@angular/compiler-cli": "2.2.1",     "@angular/core": "2.2.1",     "@angular/forms": "2.2.1",     "@angular/http": "2.2.1",     "@angular/platform-browser": "2.2.1",     "@angular/platform-browser-dynamic": "2.2.1",     "@angular/platform-server": "2.2.1",     "@ionic/storage": "1.1.7",     "dragula": "^3.7.2",     "ionic-angular": "2.0.0",     "ionic-native": "2.2.11",     "ionicons": "3.0.0",     "ng2-dragula": "^1.2.2-0",     "rxjs": "5.0.0-beta.12",     "zone.js": "0.6.26"   },   "devDependencies": {     "@ionic/app-scripts": "1.0.0",     "typescript": "2.0.9"   },   "cordovaPlugins": [     "cordova-plugin-whitelist",     "cordova-plugin-statusbar",     "cordova-plugin-console",     "cordova-plugin-device",     "cordova-plugin-splashscreen",     "ionic-plugin-keyboard"   ],   "cordovaPlatforms": [     "ios",     {       "platform": "ios",       "version": "",       "locator": "ios"     }   ],   "description": "leseschlauapp: An Ionic project" } 

1 Answers

Answers 1

seems to be a TypeScript transpiler bug

https://github.com/Microsoft/TypeScript/issues/2997

Apparently can occurs on things like this

public parent: Module | Class;

check for such union type usages, or upgrade your typescript to newer version like 2.4.*

Read More

Saturday, March 4, 2017

Creating a Master/Detail app in Plunker with Ionic 2

Leave a Comment

Building on from some good standard Ionic 2 plunkers here http://plnkr.co/edit/ZsoPeE?p=preview and http://plnkr.co/edit/WBeRRJyYucLwvckjh5W7?p=preview

Can you help tweak my Master/Detail Plunker? I thought I had all the parts in place but missing something as it produces a white screen.

Here is my attempt at a Master/Detail plunk http://plnkr.co/edit/7NHIYMA3TUdd5nOkoXyF?p=preview

import { NgModule } from '@angular/core'; import { IonicApp, IonicModule } from 'ionic-angular';  import { AppComponent } from './app.component'; import { HomePage } from '../pages/home/home'; import { MasterPage } from '../pages/master/master'; import { DetailPage } from '../pages/detail/detail';  import { Sheetsu } from '../providers/sheetsu';  @NgModule({   imports: [ IonicModule.forRoot(AppComponent) ],   declarations: [ AppComponent, HomePage, MasterPage, DetailPage],   entryComponents: [ HomePage, MasterPage, DetailPage ],   bootstrap: [ IonicApp ],   providers: [ Sheetsu ] }) export class AppModule { } 

1 Answers

Answers 1

Fixed Plunker: http://plnkr.co/edit/5V36C9QHYDGBIqSIfBUl?p=preview

You had several mistakes

1) import { Sheetsu } from '../providers/sheetsu'; <- your file is called Sheetsu, with a capital S

2) Your relative paths are wrong, you've made it complicated for yourself by putting pages: 'pages', inside your config, and for example:

import { MasterPage } from '../pages/master/master';

inside HomePage should be

import { MasterPage } from '../master/master';

3) You are using "module": "commonjs", but not taking advantage of relative html urls:

templateUrl: 'pages/master/master.html', -> `templateUrl: './master.html',` 

with moduleId: module.id inside your @Component

4) Your button click return this.http.get('../assets/sheetsu.json') should be return this.http.get('./assets/sheetsu.json')

Read More

Saturday, February 18, 2017

Use a filter or pipe to load product categories into pages in Ionic 2?

Leave a Comment

I wish to create a Ionic 2 app with 6 pages, I am unsure whether to use a Pipe or a Filter for the individual category pages and the code I need to do that.

Each category page can load the relevant products defined by the "applecat" category. Below is the API, display of the products in spreadsheet format via Google Sheets and a very quick homepage mockup idea:

https://sheetsu.com/apis/v1.0/04c2d2906a10 https://docs.google.com/spreadsheets/d/1RNLXsxTFymqRwq_S538qX1p1PAEDIEA6s5sV8etkfLU/edit?usp=sharing

enter image description here

OVERVIEW

6 pages

  • home - no products needed to load - just links to pages
  • allproducts -loads ALL products
  • ipad - loads all items listed as ipad under applecat category
  • iphone - loads all items listed as iphone under applecat category
  • keyboard - loads all items listed as iphone under applecat category
  • laptop -loads all items listed as iphone under applecat category

SCENARIO (Potential user flow)

User opens app, clicks on Home then Ipad category link (Loads all Ipad products) then comes back to Home decides to click on All (Loads ALL products), the back and clicks on another page....

PROBLEM

Will it load 2 arrays into memory/console? Should the category pages use a filter or a pipe? How should the code look for the pipe/filter in relation to my existing API call and product list array?

PROVIDERS

getRemoteData(): any{         return this.http.get('https://sheetsu.com/apis/v1.0/04c2d2906a10')                 .map(res => res.json()); } 

LIST PAGE

@Component({ selector: 'page-master', templateUrl: 'master.html', providers: [Sheetsu] }) export class MasterPage {  // declare publicly accessible variable public sheetsuData: any;  constructor(public navCtrl: NavController, public navParams: NavParams, public sheetsuService: Sheetsu) {}  ionViewDidLoad() {     this.sheetsuService.getRemoteData()     .subscribe(response => {     // assign variable (async)     this.sheetsuData = response;     }); } 

I saw an example of filter with resets but not sure whether that is applicable in this situation?

 resetData(){     this.modifiedData = JSON.parse(JSON.stringify(this.originalData));   }    filterData(){     this.modifiedData = this.modifiedData.filter((youtuber) => {         return youtuber.subscribers > 1000000;     }   } 

With so few category pages, perhaps a Pipe would be the best option for each page? Just the potential problem of multiple API calls if the users browse all 6 pages.

Preferred bounty answer : Code for pipe/filter/service, advice on best solution and why, even better a basic working example in Github (API call for Provider and list ts code is above).

Github repo for this can be viewed and forked from https://github.com/jones98/4cat

Video of app in present state (pre-category pages working) can be viewed at https://drive.google.com/file/d/0B0QBawqyq1vPZ0o4WEpaa0o0azQ/view

2 Answers

Answers 1

You can create a service that caches the data (maybe for 5 minutes, 30 minutes, one hour, or any time interval that makes sense in the context of your application) in order to avoid making so many http request, and will also return only what you need so you can use it directly in the component/view, without filtering anything.

This will not only save a lot of useless http requests being made to the server, but it will also make the app way faster since local data is going to be used most of the times the user opens the product pages.

Let's assume you already have a class for the products:

export class ProductModel {     public aw_deep_link: string;     public product_name: string;     public apple_cat: string;     //... } 

Then we can create our cache model like this:

class ProductCache {     public products: Array<ProductModel>;     public timestamp: number;      public isValid(): boolean {         if(!this.products) {             return false;         }          let isExpired = Date.now() - this.timestamp > 1800000; // 30 min         return !isExpired;     } } 

and then we can use it in our ProductCategoryService

// Angular imports import { Injectable } from '@angular/core'; import { Http } from '@angular/http';  // Rxjs imports import { Observable } from 'rxjs'; import 'rxjs/add/operator/map';  @Injectable() export class ProductCategoryService {      private cache: ProductCache;     private apiUrl: string = 'https://sheetsu.com/apis/v1.0/04c2d2906a10';      constructor(private http: Http) {         this.cache = new ProductCache();     }      public getAll(): Observable<Array<ProductModel>> {         if(this.cache.isValid()) {             // Return the products from the cache             return Observable.of(this.cache.products);         }          // Cache is empty/expired, so we need to make the http request         return this.http.get(this.apiUrl).map(res => res.json()).map(data => {             // Save the data in the cache for the next time             this.cache.products = data;             this.cache.timestamp = Date.now();              // Return the list of (all) products             return this.cache.products;         });     }      public getIpadProducts(): Observable<Array<ProductModel>> {         return this.getAll().filter((product: ProductModel) => {             return product.apple_cat.toLowerCase() === 'ipad';         });     }      public getIphoneProducts(): Observable<Array<ProductModel>> {         return this.getAll().filter((product: ProductModel) => {             return product.apple_cat.toLowerCase() === 'iphone';         });     }      // ... } 

And then just call the right method in each page, and an http request will be made only once (or every 30 min in this example) because of the product's cache.

There could be syntax errors or typos (I coded directly in the SO answer) but this should give you the idea about how to deal with the given scenario. Please let me know if something doesn't work properly, so I can help you fixing it...

UPDATE: Here you can find some information (from Angular 2 Docs) about why using pipes to filter data is not a very good approach, and this is why I recommend doing that in the service, keeping it hidden to the rest of the application (after all, each category page just wants to get the data that it needs to show, it shouldn't have to deal with all the products to then find only the ones it needs to display in the view).

Answers 2

I also should create a service called ProductCategoryService

ionic g provider ProductCategory 

And create a method which I could execute with category name as parameter

getProductsByCategoryName(categoryName): any{   return this.allProducts.filter(product => product.categoryName === categoryName); } 

In return I would get a filtered array with my products, bind that to your template and you're done.

Read More

Wednesday, February 8, 2017

Best approach on handling large dataset for offline-first Mobile Apps (PouchDB)

Leave a Comment

So I'm using Ionic v2 and using Pouch for mobile development using sqlite. Data coming from a REST API which contains something like this:

{   "record-id": "2332255",   "record-name": "record-ABC-XTY",   "record-items": [     {       "item-id": "456454",       "item-name": "item-XADD",       "category": "Cat1",       "subcategory": "Subcat1",       "location": "LocationXYZ",       "owner": "Person1",       "data-rows": [         {           "row-name": "sampleRowName1",           "row-value": "ABC-XASS"         },         {           "row-name": "sampleRowName2",           "row-value": "ABC-XASS"         }       ]     },     {       "item-id": "654645",       "item-name": "item-BNSSA",       "category": "Cat2",       "subcategory": "Subcat2",       "location": "LocationABC",       "owner": "Person2",       "data-rows": [         {           "row-name": "sampleRowName1",           "row-value": "ABC-XASS"         },         {           "row-name": "sampleRowName2",           "row-value": "ABC-XASS"         }       ]     }   ] } 

Now as you can see, the record-items could contain 100,000 items or more (est json size: 32mb). Right now I'm lost on which approach should I take. Optimized data handling is crucial and I don't know what PouchDB approach is better. Here are some of my thoughts.

  1. Save the whole JSON data as one entry for PouchDB. But I'm worried that it will take up a large memory when retrieved and will make that application slow.
  2. Chunk the record-items by one pouch entry record and retrieve it individually. I'm not sure if this is better in terms of overall performance but PouchDB record will probably be larger (?).

Also, there will be sorting, fetching all data (only the _ids and few fields just to show a list of all results) and searching.

2 Answers

Answers 1

We have a similar app that works in offline mode and stores the data locally using sqlite but the data we deal with may not be that huge. For us the data is downloaded as xml file from web service; the xml have attributes row, column, value, name etc. The app serializes the data and converts it into objects which are then inserted into sqlite (using "InsertAll"/"UpdateAll" the insert or update for items is quite fast). These xml's are loaded into UI and user can update "value" tags from UI.
Search is optimized by giving user filters so that the query is run on smaller data.

For your case I can think of 3 tables that you can use:-

1) Records (Fields:-RecordID, RecordName) 2) Items (Fields:- ItemID (PK), RecordID (FK), ItemName etc) 3) Rows (Fields:-ItemID (FK), RowName, RowValue)

After geting data from REST you can serialize the data and insert it into respective tables concurrently. Try giving users filters when it comes to search so that actual data set is smaller.

Hope it helps!

Answers 2

Your basic decision is whether to embed the data or reference it. Here are some general rules for deciding:

Embed when:

  • Data typically queried together (example: user profile)
  • Child depends on parent
  • One-to-one relationship
  • One-to-few relationship
  • Changes occur at a similar rate

Reference when:

  • Unbounded one-to-many relationship exists
  • Many-to-many relationship
  • Same data repeated in many places
  • Data changes at different rates

You're correct that if you store everything as one record you may have problems with the size. The extra storage caused by splitting it up should be inconsequential.

You'll be using views to create indexes, which then feed into your queries. How you do that will probably dominate the efficiency.

Read More

Monday, February 6, 2017

Enable pinch to zoom inside iframe - Ionic 2 AngularJS 2

Leave a Comment

I added zooming="true" inside the tag but when the page is loaded I cannot zoom to increase or decrease the view. I've also set webkitallowfullscreen mozallowfullscreen allowfullscreen to scale the page in order to fit the device screen but nothing changed and the page is still cut.

Here's my detail-page: html:

<ion-content>   <iframe sandbox class="link" frameborder="0" [src]="webPage()" zooming="true" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe> </ion-content> 

scss:

detail-page {      .scroll-content{         padding: 0px ;     }      ::-webkit-scrollbar,     *::-webkit-scrollbar {         display: none;     }      iframe.link {         width: 100%;         height: 100%;         max-width: 100%;         max-height: 100%;     }  } 

ts:

webPage() {         return this.sanitizer.bypassSecurityTrustResourceUrl(this.entry.getElementsByTagName('link')[0].textContent);     } 

1 Answers

Answers 1

You will need to track the gesture and apply the change of zoom to the iframe like this document.getElementByTagName('iframe').contentWindow.document.body.style = 'zoom:50%';

Here the zoom is set to 50%, but this can be added dynamically using the gesture event values.

Read More