Quantcast
Channel: Ionic Forum - Latest posts
Viewing all 228527 articles
Browse latest View live

How to update message of LoadingController in ionic4?

$
0
0

Any solution that how to show html content in LoadingController?


Phonegap-nfc: where is the content?

$
0
0

VERSION: Ionic 4
Plugin: phonegap-nfc

Hi everyone!

I’m trying to use this plugin (https://ionicframework.com/docs/native/nfc) and following the instructions, I should be able to read a message sent from another NFC device. The event is fired and I know something is sent, but I’m not able to understand what and where the message is stored.

This is the code:

home.page.ts

import { Component } from '@angular/core';
import {Ndef, NFC} from '@ionic-native/nfc/ngx';
import {AlertController} from '@ionic/angular';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  constructor(private nfc: NFC, private ndef: Ndef, private alertController: AlertController) { }

  readNFC() {
    this.nfc.addNdefListener(() => {
      this.presentAlert('ok');
    }, (err) => {
      this.presentAlert('ko' + err);
    }).subscribe((event) => {
      console.log(event);
      console.log(JSON.stringify(event));

      this.presentAlert('Il messaggio contiene' + event.tag + ' ' + this.nfc.bytesToHexString(event.tag.id));
    });

  }


  writeNFC() {
    this.nfc.addNdefListener(() => {
      console.log('successfully attached ndef listener');
      const message = this.ndef.textRecord('Hello world');
      this.nfc.share([message]).then(
          value => {
            this.presentAlert('ok');
          }
      ).catch(
          reason => {
            this.presentAlert('ko');
          }
      );
    }, (err) => {
      this.presentAlert('ko' + err);
    });

  }


  async presentAlert(mess) {
    const alert = await this.alertController.create({
      header: 'attenzione',
      message: mess,
      buttons: ['OK']
    });

    await alert.present();
  }
}

app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import {Ndef, NFC} from '@ionic-native/nfc/ngx';

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy },
      NFC,
      Ndef
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

This is the stringify obtained by printing the content of event:

{"isTrusted":false,"tag":{"id":[0],"techTypes":["android.nfc.tech.Ndef"],"type":"android.ndef.unknown","maxSize":0,"isWritable":false,"ndefMessage":[{"tnf":1,"type":[85],"id":[],"payload":[3,112,108,97,121,46,103,111,111,103,108,101,46,99,111,109,47,115,116,111,114,101,47,97,112,112,115,47,100,101,116,97,105,108,115,63,105,100,61,99,111,109,46,119,97,107,100,101,118,46,119,100,110,102,99,38,102,101,97,116,117,114,101,61,98,101,97,109]},{"tnf":4,"type":[97,110,100,114,111,105,100,46,99,111,109,58,112,107,103],"id":[],"payload":[99,111,109,46,119,97,107,100,101,118,46,119,100,110,102,99]}],"canMakeReadOnly":false}}

Thanks in advance for your help!

How to trigger an event when a certain slide is active?

$
0
0

Hi,
when I scroll through the slides of an ion-slider without using buttons,ì but on the screen of the phone, is there an event that can be raised when a certain slide is shown?

For example, I’d like to print an alert when the 3rd slide is shown, but at this moment I don’t know when the user is on the 3rd slide.

Fab position incorrect in ngSwitch segment

$
0
0

Ca marche aussi pour moi merci beaucoup

Property 'loadingController' does not exist

$
0
0

Thank you Rapropos. I went ahead and maintained use of the loadingcontroller only from app.component.ts:

import { NavigationCancel,

         Event,

         NavigationEnd,

         NavigationError,

         NavigationStart,

         Router } from '@angular/router';

import { Platform, LoadingController } from '@ionic/angular';

...

constructor(

    public platform: Platform,

    private splashScreen: SplashScreen,

    private statusBar: StatusBar,

    public loadingController: LoadingController,

    private router: Router

  ) 

  {

    this.initializeApp();

    // Router

    this.router.events.subscribe((event: Event) => {

      this.navigationInterceptor(event);

    });

  }

  initializeApp() {

    this.platform.ready().then(() => {

      this.statusBar.styleDefault();

      this.splashScreen.hide();

    });

  }

  private navigationInterceptor(event: Event): void {

    if (event instanceof NavigationStart) 

    {

      // Create Loader

      var loaderToShow = this.loadingController.create({

        message: 'Please wait...'

      }).then((res) => {

        res.present();

      });

      //alert("start");

    }

    if (event instanceof NavigationEnd) {

      setTimeout(() => {

        this.loadingController.dismiss();

      }, 1000);

      //alert("end");

    }

    if (event instanceof NavigationCancel) {

      setTimeout(() => {

        this.loadingController.dismiss();

      }, 1000);

      //alert("cancel");

    }

    if (event instanceof NavigationError) {

      setTimeout(() => {

        this.loadingController.dismiss();

      }, 1000);

      //alert("error");

    }

  }

Not sure how reliable this is going to be but that is what worked for me for now.

iOS 13.2 kill() returned unexpected error 1

Ion-input does not work propperly

Ionic app on iOS requires turning off Safari setting “prevent cross-site tracking”

$
0
0

I have an Ionic 4 (Cordova/Angular) app that makes CORS requests to a REST API backend with the Angular HttpClient.

The app runs fine on Android and in browser.
But on iOS it won’t run unless the user first goes to Settings > Safari, and turns off the setting “prevent cross-site tracking”, which is on by default.
Obviously it’s unreasonable to require all users to change that setting.

Also, the won’t run on the Mac’s iOS simulator at all, even if I turn off that setting in the simulator’s settings, making it extremely hard for development.

TIA for any help


navigator.contactsPhoneNumbers access a variable

$
0
0

Hello together

Can someone tell me how I can access a variable that I defined on top of my script?

See example:

public my_variable = ;

constructor(…

getContacts(){
navigator.contactsPhoneNumbers.list(function(contacts) {
console.log(contacts.length + ’ contacts found’);
for(var i = 0; i < contacts.length; i++) {
console.log(contacts[i].id + " - " + contacts[i].displayName);
for(var j = 0; j < contacts[i].phoneNumbers.length; j++) {
var phone = contacts[i].phoneNumbers[j];
// here is the problem: null is not an object this.my_variable
this. my_variable.push(phone.number);
}
}
}, function(error) {
console.error(error);
});
}

Thank you so much for your help.

Cheers

Ion-content is not a known element

$
0
0

Thank you for your time repropos. I thought it would be enough with this in app.module.ts:

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';

imports: [BrowserModule,

            IonicModule.forRoot(),

            ReactiveFormsModule,

            AppRoutingModule],

I am getting closer to the problem. When I created the component, I used this command:

ionic generate component MyAdd --spec=false

I noticed if I leave out the --spec=false, then everything works.

I am guessing as you mentioned, there is something wrong with the command. But is there an easier (global) way I dont have to import IonicModule into every component I create? Thank you.

Inappbrowser android camera problem and alternative approach

$
0
0

I have an existing web site and i wan to make it app. I decided to go with ionic and cordova-plugin-inappbroser.
My web site has some pages that captures images of user via camera. It works on mobile and desktop browsers very well, but i couldnt make it work inside IAB.
Here is my question.
Is there any alternative for cordova-plugin-inappbroser which would work without problem.
Or any suggestions welcomed.
Thanks

After splash screen, display white screen long time

$
0
0

Mesmo efetuando todos os ajuste indicados, ficou aproximadamente um segundo de tela branca após o splash. Resolvi atrasando o encerramento do splash por um segundo para cobrir a tela branca deselegante. Em “app.component.ts” ajuste da seguinte forma…

initializeApp() {

this.platform.ready().then(() => {

  this.statusBar.styleDefault();

  setTimeout(() => { 

    this.splashScreen.hide();

  }, 1000);

});

}

What difference does ion-list make?

$
0
0

Hi, i would like to know if ion-list provides any usability or performance improvement over not using it. Im asking because im able to scroll over my content even without putting it inside ion-list and using Google Lighthouse for profilling i discovered that ion-list takes 1sec more to load than putting my content direct inside ion-content (not in this small example, but in a real project).

For example:

<ion-content>
 <ion-list>
          <ion-card ng-for="let item of list">
              
                <ion-card-header>
                  {{item.title}}
                </ion-card-header>
              
                <ion-card-content>
                 {{item.desc}
                </ion-card-content>
              
              </ion-card>
    </ion-list>
</ion-content>

Is any faster or has any advantage over:

<ion-content>
          <ion-card ng-for="let item of list">
              
                <ion-card-header>
                  {{item.title}}
                </ion-card-header>
              
                <ion-card-content>
                 {{item.desc}
                </ion-card-content>
              
              </ion-card>
</ion-content>

Thanks in advance.

[best practice] Chained API requests

$
0
0

Hi,

I’m currently developing an application and I now take care of the API part.
And I wonder what is the best method, the best practice to make API calls.

Indeed, I have the following data/table in my DB:
image

So I need to, in this order:

  1. Request the Class1, save “name” in “myPrintedData”
  2. Take the externa_id1 and make the findbyID request, then add the property to “myPrintedData”
  3. Take external_id2 and make a findById request, then add the property to “MyPrintedObject”
  4. Return the nex object

I found the chained API calls really messy, is it really the best way to achieve this kind of data request ?
Do I needs to create an API endpoint that perform this job ?
Do I need to modify the db tables ?

Or is it ok ? :slight_smile:
Thanks

Ionic 4 - XMLHttpRequest throw error

$
0
0

Hi everyone,

I am using ionic 4, for login I am using above code. This code was working in real test android devices which have apk already but today code is triggered onerror with 0 error status. I tried in different android device, everything is okey. Can you help me?
in real

  login() {
    this.isSubmitted = true;
    if (!this.loginModel.isValid()) return;

    var xhr = new XMLHttpRequest();
    xhr.open("POST", server_url2 + "/oauth/token", true);
    xhr.withCredentials = false;
    xhr.setRequestHeader("content-type", "application/x-www-form-urlencoded");
    var requestParams = "grant_type=password&username=" + encodeURIComponent(this.loginModel.username) + "&password=" + encodeURIComponent(this.loginModel.password);
    this.loadingService.showLoader(this.loading);
    xhr.send(requestParams);
    xhr.onload = () => {
      if (xhr.status == 200) {
        let response = JSON.parse(xhr.responseText);
        this.storage.set("token", response['access_token']);
        //localStorage.setItem("token", response['access_token']);
        if (this.loginModel.username === "halim.terzioglu" || this.loginModel.username === "gorkem.azder"
          || this.loginModel.username === "ngssrgunaydin") {
          this.isAdmin = true;
          localStorage.setItem("adminUser", this.loginModel.username);
          this.appPages.push({
            header: 'Test News',
            url: '/news-test',
            icon: '../theme/icons/menu/ic-map-off.svg',
            selectedIcon: '../theme/icons/menu/ic-map-active.svg',
            expanded: false,
          });
        }
        this.isLogged = true;
        this.show = true;
        this.loadingService.hideLoader();
        this.router.navigateByUrl("/home");
      }
      else {
        //localStorage.removeItem('token');
        this.storage.remove("token");
        localStorage.removeItem('adminUser');
        this.loadingService.hideLoader();
        this.alertService.showAlert("Something went wrong", "Username or password is incorrect.");
      }
    };
    xhr.onerror = () => {
      this.loadingService.hideLoader();
      this.alertService.showAlert('Please check your connection!', '');
    }
    
    return;
  }


Ion-list is not supported on ios devices in Ionic 4

$
0
0

Hi. I am testing my app in an ios device, specifically in iPhone 7. I also tested in in iPhone 10.

Although I can see my list in an Android device, I cannot see it on ios.

My list in the component:

<ion-list *ngFor="let day of newArray; let i = index;" lines="none">
    <ion-item tappable class="tempAv" (click)="toggleSelection(i)">
      <div>
        <ion-img
          [src]='imageUrl + weatherForecast[day][0].icon + ".png"'
        ></ion-img>
      </div>
      <div class="dayList">
        {{ day }}
      </div>
      <div class="minTemp">
        {{ weatherForecast[day][0].minTemp }}°
      </div>
      <div class="maxTemp">
        {{ weatherForecast[day][0].maxTemp }}°
      </div>
    </ion-item>

    <div *ngIf="weatherForecast[day] && day.open">
      <ion-grid>
        <ion-row nowrap>
          <ion-col
            class="colList"
            *ngFor="let weather of weatherForecast[day]; let j = index;"
          >
            <div>
              <div class="itemList">
                {{ weather.date | date:'h:mm a'}}
              </div>
              <div>
                <ion-img
                  class="iconItemList"
                  [src]='imageUrl + weather.icon + ".png"'
                ></ion-img>
              </div>
              <div class="itemList">
                {{ weather.temperature }}°
              </div>
            </div>
          </ion-col>
        </ion-row>
      </ion-grid>
    </div>
  </ion-list>

Geolocation is not working on Android devices, although it work on ios

$
0
0

Hi. I am using the geolocation plugin from cordova to track my location coordinates.
Although it works perfect on ios, it does not work on Android.

My code:

  getGeoLocation() {
    console.log(this.isActive);
    console.log(this.geolocation.getCurrentPosition);
    this.geolocation.getCurrentPosition({ enableHighAccuracy: false }).then((resp) => {
      this.geoLatitude = resp.coords.latitude;
      this.geoLongitude = resp.coords.longitude;
      const city = {
        isActive: this.isActive,
        latitude: this.geoLatitude,
        longitude: this.geoLongitude
      };
    }).catch((error) => {
      console.log('Error getting location', error);
    });
  }

My AndroidManifest.xml:

<?xml version='1.0' encoding='utf-8'?>
<manifest android:hardwareAccelerated="true" android:versionCode="1" android:versionName="0.0.1" package="io.ionic.starter" xmlns:android="http://schemas.android.com/apk/res/android">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:networkSecurityConfig="@xml/network_security_config" android:supportsRtl="true" android:usesCleartextTraffic="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <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" />
    <uses-feature android:name="android.hardware.location.gps" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</manifest>

How to text-overflow: ellipsis inside ion-item?

$
0
0

Hey guys, I got an issue here. I want to hide a long string content using “…” at the end, instead of hiding it normally. Here is my code:

<ion-list class="ion-no-padding list-settings dark-background ion-margin-top">
...
...
...
      <ion-item class="ion-no-padding content-margin-horizontal dark-background">
                <ion-col>
                    <ion-label>
                        <h2 class="toggle-label">E-mail</h2>
                    </ion-label>
                </ion-col>
                <ion-col>
                    <p class="data-collaborator ellipsis">{{user?.get('username')}} </p>
                </ion-col>
            </ion-item>     

Here is how my view look like atm. I want the “…” on the end. “Ellipsis” class has “overflow: hidden; text-overflow: ellipsis;” on it, but it doesn’t work. Any one?

Ion-list is not supported on ios devices in Ionic 4

$
0
0

Please share more information to reproduce it…
For me the content of you component you posted looks correct on the first look.
There is no reason for me why this should not work also on ios-platform.

Do you have eventually a problem on your ios-device-simulator?

Is really the ios-list component the problem or causes another thing the problem?

Does the problem with your ios-component appear everywhere in your application or only on one page?

You see…I have a lot of questions :wink:

So please share more details…

Tabs Routing Module Error

$
0
0

This also allows you to handle errors before routing to the component.

Viewing all 228527 articles
Browse latest View live


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