How to access a variable from one page to another in Ionic version 3

Is it possible to use a variable declared within a function in another page? Here's the scenario: On the home page, I capture an image using the following code:

capture(event, fab: FabContainer) {
fab.close();
const cameraOptions: CameraOptions = {

  quality: 50,
  destinationType: this.camera.DestinationType.DATA_URL,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE,
  correctOrientation: true


};

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

  this.captureDataUrl = ('data:image/jpeg;base64,' + imageData);
  this.upload();
}, (err) => {

});

}

Now I want to pass this.captureDataUrl to a filter page, perform some operations, and then send it back to the home page to update the existing image. Is this achievable?

Answer №1

If you are looking to incorporate events into your application, follow these steps:

On your home page, you can implement the following code snippet:

capture(event, fab: FabContainer) {
fab.close();
const cameraOptions: CameraOptions = {

  quality: 50,
  destinationType: this.camera.DestinationType.DATA_URL,
  encodingType: this.camera.EncodingType.JPEG,
  mediaType: this.camera.MediaType.PICTURE,
  correctOrientation: true


};

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

  this.captureDataUrl = ('data:image/jpeg;base64,' + imageData);
  this.events.publish('pictureEvent',{dataUrl:this.captureDataUrl})
  this.upload();
}, (err) => {

});
}

Then, on your filter page, subscribe to the event and handle it accordingly:

import { Events } from 'ionic-angular';
...
constructor(private events:Events){
this.events.subscribe('pictureEvent',dataUrl=>console.log(dataUrl))
...
}

Answer №2

Resolved with the help of navCtrl and navParams

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

Alert: Angular has detected that the entry point '@libray-package' includes deep imports into 'module/file'

Recently updated the project to Angular 9.1 and now encountering multiple warnings from the CLI regarding various libraries, such as these: Warning: The entry point '@azure/msal-angular' includes deep imports into 'node_modules/msal/lib-com ...

Guide to creating a unit test for canActivate guard in Angular routing

Seeking guidance on writing a unit test for angular routing with the canActivate guard. Encountering an error when using the guard on routes, but no error is thrown without it. Would appreciate a suitable example along with an explanation. app-routing.mod ...

Ways to enhance TypeScript definitions for Node.js modules

Using the nodejs module "ws", I installed typings using typings i dt~ws import * as WebSocket from "ws"; function add(client:WebScoket){ let cid = client.clientId; } I am trying to Expand the WebSocket object with a property called clientId, but I&a ...

Creating a custom decision tree in Angular/JS/TypeScript: A step-by-step guide

My current project involves designing a user interface that enables users to develop a decision tree through drag-and-drop functionality. I am considering utilizing GoJS, as showcased in this sample: GoJS IVR Tree. However, I am facing challenges in figuri ...

Angular's getter value triggers the ExpressionChangedAfterItHasBeenCheckedError

I'm encountering the ExpressionChangedAfterItHasBeenCheckedError due to my getter function, selectedRows, in my component. public get selectedRows() { if (this.gridApi) { return this.gridApi.getSelectedRows(); } else { return null; } } ...

A versatile function capable of invoking two APIs simultaneously, with one of them being designed to return an array

Here is the code snippet that I am working with: getElements(apiUrl: string): Observable<Element[]> { return this.httpClient.get<any>(apiUrl + 'test/elements').pipe( catchError(error => { if(error.status === ...

Learn the method for type casting variables in Svelte 3 reactive syntax

I'm struggling with typing Svelte 3 reactive syntax variables. <script lang="ts"> import type { Player, Team } from "./types"; import { DEFAULT_PLAYER } from "./utils"; $: player = DEFAULT_PLAYER as Player; ...

Load Angular component on demand with necessary dependencies

Searching for an elegant solution (without resorting to private APIs) to create a widget-style dashboard. The goal is to dynamically load components based on user role. Is there a way to import a component and its dependencies included in the component&ap ...

Can you explain the TypeScript type for the queryKey in React Query?

Currently utilizing react query in conjunction with typescript. What should be the type of arguments passed to the function? export const useIsTokenValid = () => { const { data: token } = useQuery<string | null>(['token'], getToken, { r ...

uncertainty surrounding the usage of static integers and how to incorporate them into printf statements

Kindly test out this code and provide me with your responses: #include <stdio.h> int func() { static int n = 0; n++; return n; } int main() { /*int first = func(); int second = func();*/ printf(" first call : %d \n second call : ...

Displaying the preselected option in a Select dropdown menu using Angular

Here is the code snippet I have: <select label="people" id="ppl" [(ngModel)]="Selectedppl" (ngModelChange)="onPplSelection($event.target.value)"> <option>select people</option> <option *ngFor="let x of peopleList" [ngValue]="x"> ...

Angular Pipe -- Implicit type 'any' error occurs when trying to index type 'string' with an expression

Encountering an error while constructing the time ago pipe: Obtaining an implicit 'any' type due to inability to index type with a 'string' expression if (value) { const seconds = Math.floor( (+new Date() - +new Date(Numb ...

Ways to transfer information from HTML form components to the Angular class

I am currently working with angular 9 and I have a requirement to connect data entered in HTML forms to the corresponding fields in my Angular class. Below is the structure of my Angular class: export interface MyData { field1: string, textArea1 ...

What is the best way to structure a nested object model in Angular?

Issue occurred when trying to assign the this.model.teamMembersDto.roleDto to teamMembersDto. The error message states that the property roleDto does not exist on type TeamMembersDropdownDto[], even though it is nested under teamMembersDto. If you look at ...

Difficulty with validating form groups in PrimeNG calendar

I am currently implementing validation for my form. The discount field must not be empty and its value should range from 0 to 100, while the time_from and time_to fields cannot be left empty. However, I am facing an issue with firing the validation process ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

Encountering the following issue: Unhandled Promise Rejection - TypeError: Unable to access property 'value' of null after implementing ngAfterViewInit in the code

I'm attempting to display a Google Map using the place_id extracted from an HTML value. activity-details.page.html <ion-col> <div id="map"></div> <div ...

The specified "ID" type variable "$userId" is being utilized in a positional context that is anticipating a "non-null ID" type

When attempting to execute a GraphQL request using the npm package graphql-request, I am exploring the use of template literals. async getCandidate(userId: number) { const query = gql` query($userId: ID){ candidate( ...

When is the right time to develop a Node.js application using Typescript with dockerization

Currently, I am developing a full stack TypeScript application using Express for the server and React for the client. The folder structure of my project is organized as shown below: . ├──client/ <-- React app ├──server/ <-- Express serve ...

What are some methods for utilizing the "name" attribute within React components?

About My Coding Environment Utilizing TypeScript and ReactJS The Issue with Using name as an Attribute Encountering the following error: Type '{ name: string; "data-id": string; "data-type": string; }' is not assignable to ...