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

Reading local json file

$
0
0

The easiest way is to use fetch() function like that:

    readJsonData(){    
            fetch("../../assets/data/Parameters.json").then(res=>res.json()).then(json=>{
                console.log("OUTPUT: ", json);
                //DO YOUR STAFF
            });
    }```

Getting local JSON data

$
0
0

Better use the fetch() function than http.get:

            fetch("../../assets/data/Parameters.json").then(res=>res.json()).then(json=>{                
                //DO YOUR STAFF
            });

Ionic 4: Log in as a different user, previous user's data still shows

$
0
0

Here’s the code…

the authentication/login service

///auth.service.ts
loginUser(value){
   return new Promise<any>((resolve, reject) => {
     firebase.auth().signInWithEmailAndPassword(value.email, value.password)
     .then(
       res => resolve(res),
       err => reject(err))
   })
  }

logoutUser(){
    return new Promise((resolve, reject) => {
      if(firebase.auth().currentUser)
      {
        this.storage.clear()
        .then(()=>{
          console.log("storage cleared. logging out");
          return firebase.auth().signOut()
        })
        .then(() => {
          resolve(true);
        }).catch((error) => {
          reject(error);
        });
      }
    })
  }

After logging, the following retrieves the user’s business info…

///home.ts

//The following code used to be in ngOnInit(), but wasn't called after relogging in as a different user, so I moved it here. It gets called each time, but .getFromLocal() doesn't call the service's constructor after the 2nd login
ionViewDidEnter()
  {console.log("businessaccount ionViewDidEnter");
    this.segment = 'requests';
    this.businessSrv.getFromLocal().subscribe((b)=>{
      this.business=b;
      console.log(this.business);
      if (this.business) this.getInfo();
    })
  }
//business.service.ts

 private businessSubject:BehaviorSubject<Business> = new BehaviorSubject<Business | undefined>(undefined);
//this constructor is called after the first login, but not after logging out and logging in as a different user
  constructor(private fbServ: FirebaseService, private _storage: Storage) 
  {
     console.log("LOGGED IN USER: ",this.fbServ.getLoggedinUser());
   this.fbServ.get('businesses', ['userId|==|'+this.fbServ.getLoggedinUser().email]) //gets the business info from Firebase
    .subscribe((biz)=>{
      if (biz == undefined) return null;
      console.log(biz[0]);
      this.businessSubject.next(biz[0] as Business);
      return this._storage.set('business',biz[0]);
    })
  }

getFromLocal(): Observable<Business | undefined>
  {
    return this.businessSubject.asObservable();
  }

  setInLocal(biz: Business): void
  {
    this.businessSubject.next(biz);
    this._storage.set('business',biz);
    console.log("biz saved:", biz);
  }

Thanks.

Disable buttons inside side menu in ionic

$
0
0

What if I want to disable a button based on a condition inside the side menu? The condition needed to check will be available only after I login to the application. In the app.component.ts I’m defining my pages like

this.pages = [
 {
   title: "a",
   component: aPage,
   src: "..",
 }, ......, {}
]

And in my app.html I’m using ngFor inside a button to loop through the pages to display like

<ion-menu [content]="content side="right persistent="true" (ionOpen)="openMenu()">
 <ion-header>
 ......
 </ion-header>
 <ion-content>
  <ion-list>  
  <button 
      id="{{p.title}} 
      menuClose 
      ion-item 
     *ngFor="let p of pages"
     (click)="openPage(p)"
   ><span>{{p.title}}</span></button>
  </ion-list>
 </ion-content>
</ion-menu>

I want to disable a button based on a condition hot to do that ?

How to changes error messages Language

$
0
0

Hello, everyone, I’m facing a new challenge, my error messages are in French, How can I change the language to english, please:

ionic : Impossible de charger le fichier C:\Users\adam\AppData\Roaming\npm\ionic.ps1, car l’exécution de scripts est désactivée sur ce système. Pour
plus d’informations, consultez about_Execution_Policies à l’adresse https://go.microsoft.com/fwlink/?LinkID=135170.
Au caractère Ligne:1 : 1

  • ionic serve
  •   + CategoryInfo          : Erreur de sécurité : (:) [], PSSecurityException
      + FullyQualifiedErrorId : UnauthorizedAccess

Cordova tries to add a plugin as a platform on ionic cordova platform add ios

$
0
0

The message saying the cordova-plugin-voippush is not a valid platform is an incorrect message. Seems like the issue has more to deal with the missing plugin even though it is clearly in node_modules

Electron - falling at the first hurdle

$
0
0

Thanks for responding Mike, and putting my mind at rest :+1:

inAppBrowser target '_blank' not working in Ionic App

$
0
0

Hello all!

I’m trying to get the browser to launch within my Ionic App. I’ve been following the directions on ‘https://ionicframework.com/docs/native/in-app-browser#usage’ which references the github docs: ‘https://github.com/apache/cordova-plugin-inappbrowser’.

This is my code:

import { InAppBrowser } from '@ionic-native/in-app-browser/ngx';
---
const browser = this.iab.create('https://google.com/', '_blank');
                  browser.on('loadstop').subscribe(event => {
                    console.log('Loaded!')
                    browser.close();

Now you’ll notice that I’m using ‘create’ instead of ‘open’ referenced on the github docs. When I hover over create, it gives me the same function description as does ‘open,’ specifically:

Opens a URL in a new InAppBrowser instance, the current browser instance, or the system browser.

@param url — The URL to load.

@param target — The target in which to load the URL, an optional parameter that defaults to _self.

So if create works with the same functionality as open, referenced in the Github doc - why when I pass in ‘_blank’ it opens up a separate window to Google, instead of within the App? (Also that subscribe call fails as it doesn’t catch the ‘loadstop’ event.) If it helps, I’m running this ionic app in my Lab environment using ‘Ionic serve -l’.

Thanks for your help in advance!


Ionic React type error in Android Studio

$
0
0

Hi there, i got this error in android studio with the tabs starter project of ionic/react. This didn’t happened when i tried with ionic/angular.

E/Capacitor/Console: File: http://localhost/static/js/12.6aa42ace.chunk.js - Line 2 - Msg: Uncaught (in promise) TypeError: Object.entries is not a function

Any of you had this problem?

UIWebView references in blank project

$
0
0

Hi there,

I am going through a nightmare regarding the UIWebView depreciation. I am in the process of identifying the cordova plugins and hopefully will find solutions. However, when I start from a blank ionic project, I still see references with respect to UIWebView and puzzled by it. Below please find the steps I followed:

  1. ionic start testProject blank --cordova
  2. Add the below into the ios section of the config.xml:
<preference name="WKWebViewOnly" value="true" />
<feature name="CDVWKWebViewEngine">
      <param name="ios-package" value="CDVWKWebViewEngine" />
</feature>
<preference name="CordovaWebViewEngine" value="CDVWKWebViewEngine" />
  1. ionic cordova prepare ios
  2. cd platforms/ios
  3. grep -Ri UIWebView

At this point, I see references at CDVUIWebViewEngine.m

If I were to install the following:

ionic cordova plugin add cordova-plugin-inappbrowser
npm install @ionic-native/in-app-browser

I also see references related to inappbrowser

I am not sure what is going on with such a basic structure. I’d grateful for any pointer you may have as I have been pulling my hairs for the last two days.

Below is my setup:

Ionic:

   Ionic CLI                     : 6.7.0 (/home/doug/.npm-global/lib/node_modules/@ionic/cli)
   Ionic Framework               : @ionic/angular 5.1.1
   @angular-devkit/build-angular : 0.901.7
   @angular-devkit/schematics    : 9.1.7
   @angular/cli                  : 9.1.7
   @ionic/angular-toolkit        : 2.2.0

Cordova:

   Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
   Cordova Platforms : ios 5.1.1
   Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.2.1, (and 6 other plugins)

Utility:

   cordova-res                          : 0.14.0
   native-run (update available: 1.0.0) : 0.2.9

Thanks,

Doug

Create ionic 4 Project

$
0
0

Downgrade your CLI version of ionic to 4 in global setting. then you can create ionic 4 version apps.

Ionic 4: Log in as a different user, previous user's data still shows

$
0
0

I’m going to start with the smaller problems and work towards the bigger ones:

The good news is that you’ve already got the infrastructure in place for communicating externally-initiated changes to the active Business to places like HomePage. However, the chain seems to be broken by the fact that FirebaseService.getLoggedInUser doesn’t itself expose an Observable (that can be triggered upon logout). If you augment getLoggedInUser with a watchLoggedInUser that exposes an Observable<User>, and somehow have logoutUser cause it to emit undefined, then BusinessService can subscribe to that in its constructor, instead of simply taking a snapshot.

How to kill a page?

$
0
0

Can you back up and describe in non-technical terms what you mean by “kill that page”?

How to kill a page?

$
0
0

of course…

my problem:

In tab 1, I have a page called NewObject. That page is creating a new object and displaying it in the Tab2 page. I can edit the object (it goes back to the same page in Tab1) in the Tab 2. In the NewObject page I have a button delete. When I click the delete button I want that page to disappear, being the root a page called “Home” in Tab1. The problem here is when I edit the object when I come back to the Tab1, the NewObject page is still there because when I click the button I have to go back to the Tab2, so the TAB1 NewObject stays alive. How can I get rid of this link?

Is there anyway to solve this?

How to kill a page?

$
0
0

Probably, but I fear that tabs are not a good fit for this structure. Tabs are at their best when hosting self-contained “sub-apps” that are independent of one another (such as “menu”, “hours”, “order history”, &c for a restaurant app). I get that it appears initially seductive to wall off different functionality applying to the same business object in tabs - I’ve done this before also, but have found it does not hold up well from a UX perspective, aside from any technical trouble you’ve run into.

Without knowing more about what your business-level domain looks like, I can’t say much more concretely, but generally speaking I think my first instinct would be a breadcrumb summary/detail design, where you have a summary page that is capable of:

  • spawning new objects,
  • descending into existing ones by navigating to their detail page,
  • deleting unwanted objects

I would have the detail page take its notion of what constitutes “the currently focused object” from a service that is injected by both the summary and detail pages. The detail page could have a breadcrumb link back to the summary page (and also, if desired, a “delete this object” button that does the deletion and returns to the summary).

I believe this approach would design away the specific technical problem you’re having, as well as resulting in a more intuitive interface for the user.


How to kill a page?

$
0
0

Thank you so much for your insight, I thought I was just being dumb by not being able to perform this. I started to use ionic about 5 months and I don’t have much experience.
Thank you

White screen Android

$
0
0

Hi Cephaz, i had the same problem and i did this, but it didn’t solved it. Did you do anything else? do you have any extra configurations? Thanks

Paypal Integration TypeError: Object(...) is not a function

$
0
0

hi,

i am right into the PayPal payment but i get the following error:

CheckoutPage.html:152 ERROR TypeError: Object(...) is not a function

    at PayPal.init (index.js:10)

    at CheckoutPage.webpackJsonp.352.CheckoutPage.placeOrder (checkout.ts:94)

    at Object.eval [as handleEvent] (CheckoutPage.html:152)

    at handleEvent (core.js:13589)

    at callWithDebugContext (core.js:15098)

    at Object.debugHandleEvent [as handleEvent] (core.js:14685)

    at dispatchEvent (core.js:10004)

    at core.js:10629

    at HTMLButtonElement.<anonymous> (platform-browser.js:2628)

    at t.invokeTask (polyfills.js:3)

    at Object.onInvokeTask (core.js:4751)

    at t.invokeTask (polyfills.js:3)

    at r.runTask (polyfills.js:3)

    at e.invokeTask [as invoke] (polyfills.js:3)

    at p (polyfills.js:2)

    at HTMLButtonElement.v (polyfills.js:2)

My checkout.ts file is:


import { Component } from '@angular/core';
import { NavController, NavParams, AlertController } from 'ionic-angular';
import { Storage } from '@ionic/storage';
import * as WC from 'woocommerce-api';
import { HomePage } from '../home/home';
import { PayPal, PayPalPayment, PayPalConfiguration } from '@ionic-native/paypal/ngx';
 
@Component({
  selector: 'page-checkout',
  templateUrl: 'checkout.html',
})
export class CheckoutPage {
 
  WooCommerce: any;
  newOrder: any;
  paymentMethods: any[];
  paymentMethod: any;
  billing_shipping_same: boolean;
  userInfo: any;
 
  constructor(public navCtrl: NavController, public navParams: NavParams, public storage: Storage, public alertCtrl: AlertController, public payPal: PayPal) {
    this.newOrder = {};
    this.newOrder.billing_address = {};
    this.newOrder.shipping_address = {};
    this.billing_shipping_same = false;
 
    this.paymentMethods = [
      { method_id: "bacs", method_title: "Direct Bank Transfer" },
      { method_id: "cheque", method_title: "Cheque Payment" },
      { method_id: "cod", method_title: "Cash on Delivery" },
      { method_id: "paypal", method_title: "PayPal" }];
 
      this.WooCommerce = WC ({
        url:"https://woocommerce-251774-1115146.cloudwaysapps.com",
        consumerKey: "ck_6c9779a96e5377a4b28df5a1aca2e8c6dbbfaae3",
        consumerSecret: "cs_5dc2811ed708448a3dfc889a0921e2e266b25813"
  
    });
 
    this.storage.get("userLoginInfo").then((userLoginInfo) => {
 
      this.userInfo = userLoginInfo.user;
 
      let email = userLoginInfo.user.email;
 
      this.WooCommerce.getAsync("customers/email/" + email).then((data) => {
 
        this.newOrder = JSON.parse(data.body).customer;
 
      })
 
    })
 
  }
 
  setBillingToShipping() {
    this.billing_shipping_same = !this.billing_shipping_same;
 
    if (this.billing_shipping_same) {
      this.newOrder.shipping_address = this.newOrder.billing_address;
    }
 
  }
 
  placeOrder() {
 
    let orderItems: any[] = [];
    let data: any = {};
 
    let paymentData: any = {};
 
    this.paymentMethods.forEach((element, index) => {
      if (element.method_id == this.paymentMethod) {
        paymentData = element;
      }
    });
 
 
    data = {
      payment_details: {
        method_id: paymentData.method_id,
        method_title: paymentData.method_title,
        paid: true
      },
 
      billing_address: this.newOrder.billing_address,
      shipping_address: this.newOrder.shipping_address,
      customer_id: this.userInfo.id || '',
      line_items: orderItems
    };
 
 
    if (paymentData.method_id == "paypal") {
 
      this.payPal.init({
        PayPalEnvironmentProduction: "YOUR_PRODUCTION_CLIENT_ID",
        PayPalEnvironmentSandbox: "ARP4uyVXQzfGXHKK25rrYghpZD7lZ-1jeiOea0K30j_iiG518jZUMfmfBc-x4KI8ZaITX_cUrmDDx056"
      }).then(() => {
        // Environments: PayPalEnvironmentNoNetwork, PayPalEnvironmentSandbox, PayPalEnvironmentProduction
        this.payPal.prepareToRender('PayPalEnvironmentSandbox', new PayPalConfiguration({
          // Only needed if you get an "Internal Service Error" after PayPal login!
          //payPalShippingAddressOption: 2 // PayPalShippingAddressOptionPayPal
        })).then(() => {
 
          this.storage.get("cart").then((cart) => {
 
            let total = 0.00;
            cart.forEach((element, index) => {
              orderItems.push({ product_id: element.product.id, quantity: element.qty });
              total = total + (element.product.price * element.qty);
            });
 
            let payment = new PayPalPayment(total.toString(), 'USD', 'Description', 'sale');
            this.payPal.renderSinglePaymentUI(payment).then((response) => {
              // Successfully paid
 
              alert(JSON.stringify(response));
 
 
              data.line_items = orderItems;
              //console.log(data);
              let orderData: any = {};
 
              orderData.order = data;
 
              this.WooCommerce.postAsync('orders', orderData).then((data) => {
                alert("Order placed successfully!");
 
                let response = (JSON.parse(data.body).order);
 
                this.alertCtrl.create({
                  title: "Order Placed Successfully",
                  message: "Your order has been placed successfully. Your order number is " + response.order_number,
                  buttons: [{
                    text: "OK",
                    handler: () => {
                      this.navCtrl.setRoot(HomePage);
                    }
                  }]
                }).present();
              })
 
            })
 
          }, () => {
            // Error or render dialog closed without being successful
          });
        }, () => {
          // Error in configuration
        });
      }, () => {
        // Error in initialization, maybe PayPal isn't supported or something else
      });
 
 
 
 
 
    } else {
 
      this.storage.get("cart").then((cart) => {
 
        cart.forEach((element, index) => {
          orderItems.push({
            product_id: element.product.id,
            quantity: element.qty
          });
        });
 
        data.line_items = orderItems;
 
        let orderData: any = {};
 
        orderData.order = data;
 
        this.WooCommerce.postAsync("orders", orderData).then((data) => {
 
          let response = (JSON.parse(data.body).order);
 
          this.alertCtrl.create({
            title: "Order Placed Successfully",
            message: "Your order has been placed successfully. Your order number is " + response.order_number,
            buttons: [{
              text: "OK",
              handler: () => {
                this.navCtrl.setRoot(HomePage);
              }
            }]
          }).present();
 
        })
 
      })
 
    }
 
 
  }
 
}

Background images are not loading

$
0
0

Hello everyone,
I’m trying to add a background image on my sidemenu
the main problem is that the image is loading sometimes, and sometimes not!
it’s really weird now I’ve been trying to fix for hours and I’m so tired, and none of the solutions on the forum helped me.
My css:

.bg-image{

  --background: url('/assets/imgs/menubg1.png') no-repeat center center fixed;

  background: url('assets/imgs/menubg1.png') no-repeat center center fixed;

  -webkit-background-size: cover;

  -moz-background-size: cover;

  -o-background-size: cover;

  background-size: cover;

}

My html

<ion-content class="bg-image">

      <ion-list >

        <ion-list-header >

          <ion-thumbnail item-left>

            <img  src="assets/imgs/logo.png"/>

          </ion-thumbnail>

          <h3 style="font-family: 'Trebuchet MS', 'Lucida Sans Unicode', 'Lucida Grande', 'Lucida Sans', Arial, sans-serif;">How to fit</h3>

        </ion-list-header>

        <button    menuClose ion-item *ngFor="let p of pages" (click)="openPage(p)">

          <ion-icon [name]="p.icon" item-left></ion-icon>

            {{p.title}}

        </button>

      </ion-list>

    </ion-content>

Paypal Integration TypeError: Object(...) is not a function

$
0
0

Please post the entire dependencies stanza of package.json.

Viewing all 231637 articles
Browse latest View live


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