Retrieve class attributes within callback function

I have integrated the plugin from https://github.com/blinkmobile/cordova-plugin-sketch into my Ionic 3 project.

One remaining crucial task is to extract the result from the callback functions so that I can continue working with it.

Below is a snippet of my code:

anhangArray: Array<{ name: string, value: string }>=[];



  takePhoto() {
  const options: CameraOptions = {
  quality: 100,
  destinationType: this.camera.DestinationType.FILE_URI,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE,
  correctOrientation: true,
  allowEdit: false,
}

this.camera.getPicture(options).then((imageData) => {

  // imageData can be base64 encoded or a file URI
  // If it's base64:
  //base64Image = 'data:image/jpeg;base64,' + imageData;
  //>>> FILE_URI
  this.getSketch(imageData);

}, (err) => {
  // Handle error
});
}

getSketch(src: string) {
window.navigator.sketch.getSketch(this.onSuccess, this.onFail, {
  destinationType: window.navigator.sketch.DestinationType.DATA_URL,
  encodingType: window.navigator.sketch.EncodingType.JPEG,
  inputType: window.navigator.sketch.InputType.FILE_URI,
  inputData: src
});
}

onSuccess(imageData) {
var _mythis = this;
if (imageData == null) { return; }

// Perform further actions here!
setTimeout(function () {
  if (imageData.indexOf("data:image") >= 0) {
  } else {
    imageData = "data:image/jpeg;base64," + imageData;
  }
  _mythis.anhangArray.push({ name: "anhang_" + parseInt(_mythis.user._kunnr), value: imageData });
  console.log(this.anhang);

}, 0);
}

Error: Uncaught TypeError: Cannot read property 'anhangArray' of undefined

Answer №1

The main issue lies in the usage of window.navigator.sketch.getSketch(). When calling window.navigator.sketch.getSketch, it triggers your callback function this.onSuccess, causing a change in scope for the callback. To resolve this problem, you can modify the implementation as shown below.

getSketch(src: string) {
  window.navigator.sketch.getSketch(imageData => {
    this.onSuccess(imageData);
  }, error => {
    this.onFail(error);
  }, {
    destinationType: window.navigator.sketch.DestinationType.DATA_URL,
    encodingType: window.navigator.sketch.EncodingType.JPEG,
    inputType: window.navigator.sketch.InputType.FILE_URI,
    inputData: src
  });
}

Answer №2

another solution is available:

this.camera.takePicture(options).then((imageData) => {

  // imageData can be a base64 encoded string or a file URI
  // If it's base64:
  //base64Image = 'data:image/jpeg;base64,' + imageData;
  //>>> FILE_URI
  this.retrieveSketch(imageData).bind(this);

In this approach, the .bind(this) function sends the scope back to the original caller.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Importing/Requiring an External Module in Typescript Node using a Symbolic Link in the

I am in the process of migrating a Node + Express application to TypeScript and have encountered an issue with using external modules. Previously, I was utilizing the "symlink trick" to avoid dealing with relative paths. This is how it used to work withou ...

Update the image source dynamically upon the opening of an accordion in Angular

I have the following HTML code snippet in my file: <div class="col-md-3 col-sm-2 col-2 collapsedData" > <a class="collapsed" data-toggle="collapse" data-parent="#accordion" href="#collapseTwo" aria-expanded="false" aria-con ...

The issue arises when attempting to make an Ajax request after changing the value of a cascading dropdown

Hey there! I'm currently working on a cascading drop-down feature where, upon change, I need to populate another field with data from the database. Unfortunately, every time I try to populate the drop-down, my AJAX call returns an error 500. I can&ap ...

Create a custom class that functions similarly to a dictionary

Is it not feasible to achieve this? interface IMap { [key: string]: string; } class Map implements IMap { public foo = "baz"; } But instead of success, I encounter the error: TS2420:Class 'Map' does not correctly implement 'IMap& ...

Efficiently incorporating styles and CSS, as well as Bootstrap CDN, into window.print() while utilizing Vue.js

I am trying to print from my Vuejs component and apply CSS and Bootstrap styles to the printed page. Currently, I am using window.print() inside the mounted lifecycle hook as shown below: export default { mounted() { ...

Issues arise with the functionality of custom jQuery sliders

I'm attempting to create a bootstrap panel slider using my own jQuery code, but it's not functioning as anticipated. My Objective: I have two links for "previous" and "next", and three panels with distinct headings. When the "previous" link is ...

Having trouble exporting a static HTML file using Next.js

https://i.stack.imgur.com/xQj7q.pngI'm a beginner in the world of React. Recently, I completed a project where I utilized "next build && next export" in my package.json file for static HTML export. By running the npm run build command, an out folder w ...

Guide on implementing ng-repeat within a nested JSON structure in your Ionic app

Struggling with implementing ng-repeat in a nested json object. { "title": "Important message 01", "img": "any url image here", "authorPhoto": "http://lorempixel.com/40/40/people/4/", "author": "John Doe", "datePos ...

Restrict the keys to only properties that have an array data type

Is there a way to limit the keyof operator to only accept keys of a specified type in TypeScript? interface Data { items: string[]; name: string; } // I want to restrict the keyof operator to only allow keys where the value is of type `F` type Key&l ...

Discrepancy in Angular Material Buttons with theme design

I recently installed Angular 10 along with Angular Materials using the command ng add @angular/material I opted for the custom theme: Purple/Green The next step was to add a Toolbar by simply copying and pasting code from Google's site. However, I a ...

Reactjs encountering issues with CSS loading correctly

Currently, I am working with reactjs and utilizing the Nextjs framework. All my "css, js, images" are stored in the "public" folder and have been included in "_app.js". However, whenever I attempt to load the "Main page" in a browser, the page does not d ...

Error in the Angular-UI calendar

I'm encountering an issue while trying to set up the angular-ui calendar. When I run it, I get the following error: TypeError: undefined is not a function at Object.eventsWatcher.onChanged (http://localhost/fisioGest/js/calendar.js:262:41) Despite b ...

Encountering an issue with Firebase authentication in Next.js: the window object is not defined

Here is some code snippets: import { initializeApp } from "firebase/app"; import { getAnalytics } from "firebase/analytics"; import { getAuth } from "firebase/auth"; const firebaseConfig = { //credentials// }; export const ...

How to dynamically assign a type based on a single choice from multiple options (props)

I have a props object that includes: { option1, option2, option3, option4, general, otherProps } The requirement is to allow only one option to be used at a time. Here are the types defined: interface MyTypes { option1: boolean option2: boolean option3 ...

Is there a way to determine which option is currently highlighted in Internet Explorer before it is actually chosen?

Despite the fact that IE does not support mouse events on <option> elements, it does highlight the option under the mouse cursor when you open a dropdown list. Is there a way in JavaScript to capture this highlighted option as the user moves the mous ...

Location of chat icon in Dialogflow messenger

After successfully embedding the Dialogflow messenger in my website, I noticed that in mobile view, the chat icon is blocking the bottom navigation bar. You can refer to the screenshot here. Is there a way to reposition the chat icon higher on the page? I ...

Exploring the AngularJS global Date timezone offset

I want to display dates based on the users' time zones. I am hoping that Angular provides a way to globally configure the Date filter for this purpose. Doing it manually for each case doesn't seem right to me. My timestamps are already passed t ...

Is it possible for Angular to retrieve information from one JSON file but not another?

After updating the names in the code to reflect the current ones, I would greatly appreciate any help or suggestions! The json file has been provided, so there's not much additional setup required. Just a heads up: I haven't created a service fi ...

How to create a sequence of queries to a mongoDB database (using mongoose) depending on a condition

Source Code let placeForSearch="hampi" let filteredHotelFacilities=req.body.filter //["Free Wifi"] let hotels = await Hotel.find({placeForSearch}) .where("facilities") .select(selectedProperties) .skip(pageNu ...

Adjusting Image Size According to Window Resize?

My current issue involves having four images displayed side by side. When the window size is adjusted or viewed on a smaller device, the layout shifts to a line jump (with three images in a row and the fourth one below). What I actually want is for all fou ...