Transferring data between components in Ionic 2: Service to Page

My service code includes two functions - one for creating a native storage with IP and port, and the other for retrieving values from the native storage.

DatabaseService

export class DatabaseService {
  ...
  public ip: string;
  public port: string;
  ...
  public createConnectionInfo(ip: string, port: string) {
    NativeStorage.setItem('connectionStorage', { ip: ip, port: port })
      .then(
        () => console.log('Stored Connection Information!'), //Working
        error => console.error('Error storing connection information', error)
      );
  }
  ...
  public getConnectionInfo() {
    this.platform.ready().then(() => {
      NativeStorage.getItem('connectionStorage').then(data => {
        this.ip = data.ip; // Storing IP in public variable
        this.port = data.port;
        console.log(this.ip); //Works
      }, error => {
        this.navCtrl.push(SettingPage);
      });
    });
  }
  ...
}

SettingPage

export class SettingPage {
  connection: any;
  service: DatabaseService;
  ip: string;
  port: string;
  constructor(public navCtrl: NavController, platform: Platform, service: DatabaseService) {
    this.service = service;
    platform.ready().then(() => {
      if(true){ 
        console.log(this.service.ip+" IP FROM THE SERVICE"); \\Trying to retrieve IP from service.
      }
    });
  }
  ...
}

I successfully created and retrieved values from the native storage, but facing difficulty passing them from my service to the setting page. Seeking guidance on resolving this issue. Your help is appreciated as I work towards finding a solution.

My Ionic Info

Cordova CLI: 6.3.1                                                                                                              
Gulp version:  CLI version 3.9.1                                                                                                
Gulp local:                                                                                                                     
Ionic Framework Version: 2.0.0-rc.1                                                                                             
Ionic CLI Version: 2.1.0                                                                                                        
Ionic App Lib Version: 2.1.0-beta.1                                                                                             
ios-deploy version: Not installed                                                                                               
ios-sim version: Not installed                                                                                                  
OS: Mac OS X El Capitan                                                                                                         
Node Version: v6.7.0                                                                                                            
Xcode version: Xcode 7.3.1 Build version 7D1014

Answer №1

If you make a few adjustments to the getConnectionInfo method, you can retrieve your IP address by returning a promise. Here is an example:

public getConnectionInfo() {
  return this.platform.ready().then(() => NativeStorage.getItem('connectionStorage'))
    .then(data => {
      this.ip = data.ip;
      this.port = data.port;
      console.log(this.ip);
      return data;
    }).catch(error => {
      this.navCtrl.push(SettingPage);
      return error;
    });
  });
}

When you are on the SettingPage, rather than directly accessing the value, you should call the getConnectionInfo method like this:

export class SettingPage {
  connection: any;
  service: DatabaseService;
  ip: string;
  port: string;
  constructor(public navCtrl: NavController, platform: Platform, service: DatabaseService) {
    this.service = service;
    platform.ready().then(() => this.service.getConnectionInfo())
      .then(() =>{
        if(true){ 
          console.log(this.service.ip+" IP FROM THE SERVICE");
        }
    });
  }
  ...
}

You may need to adjust this code slightly, but it should function correctly as it stands.

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

Update all occurrences of a particular value to null within the Realtime Database using Firebase Cloud Functions

I need to update the values of a specific userID linked to multiple post keys in my database by setting the userID to null. The userIDs are associated with post keys located in the path: posts/ivies/userIDs in my database. Take a look at how the database i ...

What is causing TypeScript to compile and remove local variables in my Angular base controller?

I am trying to develop a base controller in Typescript/Angular for accessing form data, but I'm encountering an issue where the form member seems to be getting removed during compilation and is not present in the generated JavaScript code. Could you ...

Angular's ngbdatepicker encountering RangeError: Call stack size has surpassed maximum limit

Below is the code snippet used in my angular component template. <input type="text" (click)="dp.toggle()" ngbDatepicker #dp="ngbDatepicker" id="myDatePicker" autocomplete="off" placeholder= ...

Swapping JSON: A Quick Guide

When my Angular code loads, a list of buttons (button 1, button 2, button 3, etc.) is displayed. Upon clicking any button, the console shows J-SON with varying values. Two additional buttons are present on the page for moving up and down. My dilemma arise ...

There seems to be an issue with calling this particular expression. The elements within the type 'string | ((searchTerm: string) => Promise<void>) | []' are not all callable

Here is my unique useResults custom hook: import { useEffect, useState } from 'react'; import yelp from '../api/yelp'; export default () => { const [results, setResults] = useState([]); const [errorMessage, setErrorMessage] = us ...

A guide on capturing the response in the POST method within Angular 7

I'm currently working with Angular 7 and I need a way to know if the data has been successfully saved or not. Within my web service code, I have designated "Success" as the status when data is saved correctly, and "Unsuccessful" if the data is not sa ...

Error: Unable to install Angular on WSL due to permission denied for Node

Struggling to set up angular on WSL2, with node version 17.3.1 and npm version 8.3.0 already installed. Received an error when trying the command npm install -g @angular/cli: npm ERR! code 127 npm ERR! path /root/.nvm/versions/node/v17.3.1/lib/node_module ...

Is there a way to insert a Highchart Image into a spreadsheet in Excel?

Struggling to insert a Highchart's chart image into an Excel file? The goal is to utilize the current "Export Excel" button on a website to export a static image of the Highchart displayed on the webpage directly into an excel spreadsheet. Provided be ...

Is there a way to identify and retrieve both the initial and final elements in React?

Having an issue with logging in and need to retrieve the first and last element: Below is my array of objects: 0: pointAmountMax: 99999 pointAmountMin: 1075 rateCode: ['INAINOW'] roomPoolCode: "ZZAO" [[Prototype]]: Object 1: pointAmoun ...

Cypress: Unable to properly stub API with cy.intercept()

Whenever I utilize the cy.intercept() function, the API fails to stub. cy.intercept("GET", `${API}farm/list`, { body: { statusCode: 200, message: "Request successful", result: seededFarmList, }, }); The way I import the fixture file is as ...

What is the best way to integrate properties subsets into your classes?

In my code, I am working with 3 classes ... class1 { constructor(a, b, c) { this.a = a; this.b = b; this.c = c; this.toClass2 = function() { // TODO: return this as an instance of class2; // the conversion would remove the un ...

Updating view with *ngIf won't reflect change in property caused by route change

My custom select bar has a feature where products-header__select expands the list when clicked. To achieve this, I created the property expanded to track its current state. Using *ngIf, I toggle its visibility. The functionality works as expected when cli ...

How to send a dynamic URL parameter to a function in Next.js TypeScript without using implicit typing

When utilizing the useRouter function with a parameter of type string, the following error is encountered: Type 'string | string[] | undefined' is not assignable to type 'string'. Type 'undefined' is not assignable to type & ...

NgControl was not found in the NodeInjector provider. How can I resolve this error?

https://i.sstatic.net/z4h8J.png I am encountering a problem that I have been unable to resolve despite extensive searching. Could you please provide suggestions on how to fix this issue? I have already included the following line in the application modu ...

Using Long Polling with Angular 4

I am looking for a way to monitor the progress of a certain task using API calls. To achieve this, I have developed a service that executes these API calls every 1.5 seconds Main Component private getProgress() { this.progressService.getExportPr ...

Having trouble processing images in multi-file components with Vue and TypeScript

Recently, I reorganized my component setup by implementing a multi-file structure: src/components/ui/navbar/ Navbar.component.ts navbar.html navbar.scss Within the navbar.html file, there was an issue with a base64-encoded image <img /> ...

When set to synchronize:true in Typeorm, any changes to an entity will result in the many-to

As a newcomer to typeorm, I've encountered a peculiar issue with the synchronize: true setting in my ormconfig.js. Whenever I make changes to an entity with a Many-to-Many relationship, any data present in the join table prior to the entity modificati ...

Tips for eliminating unicode characters from Graphql error messages

In my resolver, I have implemented a try and catch block where the catch section is as follows: catch (err: any) { LOG.error("Failed to get location with ID: " + args.id); LOG.error(err); throw new Error(err); ...

Vertical and horizontal tabs not functioning properly in Mat tabs

I successfully created a vertical material tab with the code below, but now I am looking to incorporate a horizontal tab inside the vertical tab. Attempting to do so using the code provided results in both tabs being displayed vertically. Below is my code ...

Error in Visual Studio with Angular 2 build: 'Promise' name not found

I recently started exploring Angular2 and followed the instructions provided in this quickstart guide: https://angular.io/guide/quickstart Everything seems to be working well after running npm install, but now I want to work on it within Visual Studio usi ...