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

Http.post with Dialogflow v2 in Ionic 4

$
0
0

Hi,

I did a Ionic bot chat with dialogflow V1. I am trying to upgrade my code to Dialogflow V2 because Dialogflow V1 API will shutdown in March 31st, 2020.

I had two problems:
1)

This is my dialogflow.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { map } from 'rxjs/operators';
import { AutenticacaoService } from '../services/autenticacao.service';

const environment = {
  clientAccessToken: '<my token from dialogflow agent console>',
};

@Injectable({
  providedIn: 'root'
})
export class DialogflowService {

  // private baseURL: string = "https://api.dialogflow.com/v1/query?v=20150910"; // OLD
  private baseURL: string = "https://dialogflow.googleapis.com/v2/projects/<my project ID>/agent"; // NEW CODE (acordind instructions -> https://dialogflow.com/docs/reference/v2-auth-setup

  private token: string = environment.clientAccessToken;

  private email: string;

  private gcloudAuth: string = "<my code indicated -> "gcloud auth application-default print-access-token">"; // see page [https://cloud.google.com/sdk/gcloud/reference/auth/application-default/print-access-token](https://cloud.google.com/sdk/gcloud/reference/auth/application-default/print-access-token) 



  ionViewWillEnter() {
    this.email = '<some email>';
  }




  constructor(
    private http: Http,
  ) {

  }

  public getResponse(query: string, email: string) {

// OLD CODE (Dialogflow v1)
    /* let data = {
      query : query,
      lang: 'pt',
      sessionId: email,
    } */

// NEW CODE TO DIALOGFLOW v2 (see site https://cloud.google.com/dialogflow/docs/quick/api#detect-intent-text-drest

    let data = {
      queryInput: {
        text: {
          query,
          languageCode: 'pt'
        }
      }
    }


    return this.http
      .post(`${this.baseURL}`, data, { headers: this.getHeaders() }).pipe(
        map(res => {
          return res.json()
        }))
  }

  public getHeaders() {
    let headers = new Headers();
    // headers.append('Authorization', `Bearer ${this.token}`); // OLD (Dialogflw v1)
    headers.append('Authorization', `Bearer ${this.gcloudAuth}`); // NEW (Dialogflow v2)
    return headers;
  }

}

This is a part of my chat bot ts code:

public sendMessage(): void {

this.dialogflowService.getResponse(this.message.content, this.email).subscribe(res => {


           //     this.mensagemobject = res.result.fulfillment.messages; // OLD (Dialogflow v1)
                this.mensagemobject = res.queryResult.fulfillment.messages; // NEW (Dialogflow v2)

         //       this.tamanho = res.result.fulfillment.messages.length; // OLD (Dialogflow v1)
                this.tamanho = res.queryResult.fulfillment.messages.length;  // NEW (Dialogflow v2)



              
                console.log(this.mensagemobject);

                for (var i = 0; i <= this.tamanho; i++) {

                  this.messages.push(
                    new Message(this.nomePersonagemAI, this.mensagemobject[i].speech, this.avatar)
                  );
                }

              });


}

I had two problems:

PROBLEM 1 (Gcloud Auth)- authentication - I ran “gcloud beta auth application-default print-access-token” in gcloud power shell console to take my gcloud auth. I putted in my ionic code (it runs), but afther some minutes, my gcloud auth expires.

run im my gcloud power shell (see https://cloud.google.com/sdk/gcloud/reference/beta/auth/application-default/print-access-token:

$ gcloud beta auth application-default print-access-token

PROBLEM 2 (INVALID_ARGUMENT):

chrome console (run with ionic serve):

"{
  "error": {
    "code": 400,
    "message": "Invalid JSON payload received. Unknown name \"query\" at 'agent': Cannot find field.\nInvalid JSON payload received. Unknown name \"sessionId\" at 'agent': Cannot find field.\nInvalid JSON payload received. Unknown name \"agent\" at 'agent': Cannot find field.",
    "status": "INVALID_ARGUMENT",
    "details": [
      {
        "@type": "type.googleapis.com/google.rpc.BadRequest",
        "fieldViolations": [
          {
            "field": "agent",
            "description": "Invalid JSON payload received. Unknown name \"query\" at 'agent': Cannot find field."
          },
          {
            "field": "agent",
            "description": "Invalid JSON payload received. Unknown name \"sessionId\" at 'agent': Cannot find field."
          },
          {
            "field": "agent",
            "description": "Invalid JSON payload received. Unknown name \"agent\" at 'agent': Cannot find field."
          }
        ]
      }
    ]
  }
}
"

My ionic app was running without any problem with dialogflow v1, but i am not been able run it (using http.post) in my ionic app.

DOES ANYONE KNOW THE RIGHT WAY TO RUN HTTP.POS IN DIALOGFLOW v2 ??? (below)

 return this.http
      .post(`${this.baseURL}`, data, { headers: this.getHeaders() }).pipe(
        map(res => {
          return res.json()
        }))
  }

Keydown event not working in Android

Http.post with Dialogflow v2 in Ionic 4

$
0
0

While you wait for better answers, I would suggest weaning this app off of Http in favor of HttpClient. That will allow you to hopefully address both problems at once: the first by migrating the authentication stuff into an interceptor, and the second at least indirectly by aligning your basic environment with that used by likely everybody else doing this with Angular today.

Updating list upon ionic storage set() completion

$
0
0

How would you access customer data from the CustomerListComponent?
For example, if you want to sort on Firstname or Lasrname?

Updating list upon ionic storage set() completion

$
0
0

Generally speaking, my first instinct would be to carry an array of customers in the component. There are several options of what to do when sorting or filtering is in place and the upstream “universe” (all customers) changes: apply our sort / filter to the new universe, ditch it and overwrite entirely, wait until filters are off to apply upstream changes. Here’s a simple example to get you started:

@UntilDestroy()
export class CustomerListComponent {
  customers: Customer[] = [];
  customerSorter?: (a: Customer, b: Customer) => number;

  constructor(private customerer: CustomerService) {
    this.customerer.getCustomers().pipe(untilDestroyed(this)).subscribe(customers = {
      this.customers = customers;
      this.sortCustomers();
    });
  }

  sortCustomers(): void {
    if (this.customerSorter) {
     this.customers.sort(this.customerSorter);
    }
  }

  sortByLastName(): void {
    this.customerSorter = (a: Customer, b: Customer) => {
      return a.lastName.localeCompare(b.lastName);
    }; 
    this.sortCustomers();
  }

  sortByFirstName(): void {
    this.customerSorter = (a: Customer, b: Customer) => {
      return a.firstName.localeCompare(b.firstName);
    };
    this.sortCustomers();
  }
}

Updating list upon ionic storage set() completion

$
0
0

So we end up with two copies in memory of the customer list !
What if I have a large list ? I was trying to keep a single copy in the provider.
Also, this.customers = customers, will it give the address of the list in the provider or a “copy” the list ?

Updating list upon ionic storage set() completion

$
0
0

Unless you’ve profiled the app and found that memory needed to store the customer list is a noticeable concern for app performance, I would suggest a working hypothesis that this would be somewhere around #724 on my list of stuff to worry about.

People watch videos and play castle tower defense games and edit photos of themselves to look like they are anime characters on the devices your app is likely to be running on. Those sorts of activities absolutely dwarf the storage (and CPU) requirements needed for slinging typical textual data around, even a lot of fairly extensive textual data. If your Customer does have super-heavy images or videos included in it, keep reading.

Yeah, this is a great question and goes to the heart of just how pathetic JavaScript’s fake “OO” really is. I think I’ve been working in JavaScript (kicking and screaming daily) for almost a decade now and still don’t really have a solid, concise recommendation for how to work with it on this topic.

I’m going to assume you’ve got some familiarity with C or another C-like language, due to your use of the term “address of”. The short answer to your question is “the address of the list”, in the sense that although everything in JavaScript is technically pass-by-value, the “value” of an object (or an array, which is a special kind of object, even though you generally shouldn’t think of them that way) is effectively a pointer in C terms, with all the baggage that goes with that.

Entire libraries like Immutable.js and Redux have sprung up attempting to deal with “when do I want a pointer copy, a shallow clone, or a deep clone?”. I have no experience yet with any of them.

But yes, you have to worry about this. When you call something like sort that modifies an array in place, everybody else holding a reference to that array gets affected. If that’s a problem, then you can start cloning things or defining ownership rules.

Again, though, textual data is super, super lightweight in today’s world. You are going to have much more urgent performance (and UI) concerns figuring out how to let users interact with lots of customers way before you have to worry about how many copies of the list you have in memory. If a Customer has heavy fields like a movie or high-res image, worry about those, but unless you’re blindly deep-cloning everything, those heavy bits will effectively be shared by reference.

No error returned but no data returned on successful json post to api

$
0
0

Hi @rapropos, I had tried with HttpClient but I kept getting CORS errors regarding existing headers and it was suggested that I use ionic native HTTP


[v4] Modal Scrolling?

$
0
0

I haven’t been able to see how to do any kind of scrolling on Modal? I have content that works great on a phone because it allows you to scroll down, however I can’t seem to be able to scroll using a Desktop Browser, any suggestions? Below is a sample, however there’s simply a bunch of stuff that is between the IonModal, I thought it would auto-scroll naturally?


        <IonModal isOpen={showModal} backdropDismiss={false}>
        </IonModal>

Updating list upon ionic storage set() completion

$
0
0

Once again, efficient answer. Thanks a lot. I’ll try worrying about stuff that matters. And i’ll keep an eye out for potential side effects of working/modifying an object taken from a provider.

Ionic Bluetooth Serial Module / Unsubscribe & UnsubscribeRawData methods missing?

$
0
0

(post withdrawn by author, will be automatically deleted in 24 hours unless flagged)

Ionic 4 Cordova Custom Plugin using Ionic-Native

$
0
0

Did you use the Ionic Native Wrapper?

Ionic Bluetooth Serial Module / Unsubscribe & UnsubscribeRawData methods missing?

$
0
0

Great, Thanks @rapropos for the quick response!

Setting up the subscription and unsubscribing this way makes sense and works well! I guess I was a bit confused as to how this subscription was working (trying to call unsubscribe/unsubscribeRawData) without storing the return value as a subscription first.

Thanks again, great support!

How to open Dialer in ionic V5?

$
0
0

hi, i need to open dialer with a phone number, im in ionic 5 but when I use the call number plugin from ionic-native, im getting the error " ‘CallNumber’ is declared but its value is never read.ts(6133)
Cannot find module ‘@ionic-native/call-number/ngx’.ts(2307)"

import { CallNumber } from '@ionic-native/call-number/ngx';

Im using capacitor, but I didnt find any plugin to use open dialer. How can i do that ?

Ionic App keeps stopping


Run webView with https

$
0
0

Perhaps my issue is a lack of understanding, or documentation. Please help clarify for me.

So if the app itself is running the webview without https/ssl -does it still communicate with outside APIs securely?

Last question, the third-party example was a reference to Stripe payments. Their frontend JS library embeds some payment UI controls, and insists that the site it’s embedded in is using https. This seems like if would be effected by the http webview, is that not right?

Требуется разработчик на ionic мобильное приложение

$
0
0

Hi @zareckii

I am interested in your requirement and will be glad to assist you as an ionic expert to give you relevant solution what you are looking for.

please reach me out through Skype : cis.am3 or email me at frank@cisinlabs.com to process further.

Regards
Frank

Community plugins installation guide not available in ionic 4 and 5

$
0
0

There is no installation commands for community plugins in ionic 4 and ionic 5. Still it is available in ionic 3. Could you include the installation commands for community plugins as well in ionic 4 and 5.

Ionic 5 - what is app-explore-container?

$
0
0

DOH! :face_with_monocle:

Having actually looked at the code, rather than just blindly following the good, but somewhat complex, tutorial, I can see that it is a simple example of an Ionic component that adds a link to this page…

…which seems to be a nicely updated documentation of built-in Ionic components!

Community plugins installation guide not available in ionic 4 and 5

$
0
0

i found the solution for this, there is a CSS for display: none !important, because of this the commands for installing the plugins not shown. It’s a bug

Viewing all 228653 articles
Browse latest View live


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