Transferring an array of data across different screens within an Ionic 2 application

I am a newcomer to Ionic 2 and I am encountering difficulties when it comes to passing data between pages. Within my Home.ts file, there exists a global array containing certain numbers that have been calculated. My intention is to transfer this array to my Table.ts file in order to display it within an HTML table using the *ngFor method.

Below is the function within Home.ts where I populate the array and attempt to push (I will omit the actual calculations since I am confident they are accurate).


import { Component } from '@angular/core';
import { AlertController } from 'ionic-angular';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Table } from '../table/table';

export class HomePage {

    averagesList: Array<number> = [];

    constructor(public alerCtrl: AlertController,
        public navCtrl: NavController,
        public navParams: NavParams) {}

    Calculate() {
    
        var Averages = [];

        // Calculations on the 'Averages' Array
        
        this.averagesList = Averages;

        this.navCtrl.push(Table, this.averagesList);
        
    }

}

When attempting to display this data in my Table.ts file, I receive an undefined result.


import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { HomePage } from '../home/home';

@IonicPage()
@Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class Table{

constructor(public navCtrl: NavController, public navParams: NavParams) {}

ionViewDidLoad() {
    console.log(this.navParams.get('averagesList'));
}

}

I have experimented with passing a let variable which was successful, so why does it not function as expected with arrays?

Answer №1

The error lies in utilizing

console.log(this.navParams.get('averagesList'));

In this case, 'averagesList' serves as the identifier.

To access it correctly, you must pass it like so:

this.navCtrl.push(Table,{'averagesList' : this.averagesList});

Otherwise:

If you simply send it as

this.navCtrl.push(Table,this.averagesList);

You can retrieve the value in this manner:

console.log(this.navParams.data);

Answer №2

Services are a great way to achieve this task. Similar to Angular 2, you can bring in your service within the constructor and access its properties like so:

import {OnInit} from '@angular/core';
import {someService} from ./somepath;
 ...
 export class someClass implements OnInit{
let myTempVariable; //store shared data here
constructor (private smService: someService){ ... }
ngOnInit{ 
   this.myTempVariable = this.smService.SharedServiceData;
}
...
}

Answer №3

Utilizing a service to pass nested data is recommended, especially in scenarios involving calculations objects.

You can implement a messageService and monitor changes by using the code snippet below.

import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {Subject} from 'rxjs/Subject';

@Injectable()

 export class LocalMsgService {  

private subject = new Subject();

sendMessage(message) {
    this.subject.next(message);
}

clearMessage() {
    this.subject.next();
}

  getMessage(): Observable<any> {
     return this.subject.asObservable();
  }
}

The above service can be utilized in your home.ts and table.ts components as shown below

Home.ts

    //other imports go here 
    import {LocalMsgService} from 'services/localMsg';


    @Component({
        selector: 'home-component',
        templateUrl: 'home.html'
    })
    export class HomePage {
        constructor( private msgService: LocalMsgService) {

          }

        dataToPass() {
            console.log(this.averagesList);
            this.msgService.sendMessage(this.averagesList);
        }

    }

Table.ts

       //other imports go here 
       import {LocalMsgService} from 'services/localMsg';
       import {Subscription} from 'rxjs/Subscription';


        @Component({
           selector: 'page-table',
          templateUrl: 'table.html',
        })

        export class TablePage{

            items: any;
            subscription: Subscription;

            constructor(
            public localMsgService : LocalMsgService) {
                this.subscription = this.localMsgService.getMessage().subscribe(msg => {
                    this.items = msg;
                });
            }

        }

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

I am attempting to incorporate an NPM package as a plugin in my Next.js application in order to prevent the occurrence of a "Module not found: Can't resolve 'child_process'" error

While I have developed nuxt apps in the past, I am new to next.js apps. In my current next.js project, I am encountering difficulties with implementing 'google-auth-library' within a component. Below is the code snippet for the troublesome compon ...

Utilizing Laravel's whereJsonContains for JSON Where Clauses

I am encountering an issue with queries in Laravel. Below is the code snippet in Laravel: $table_data = \App\Models\Data::where('data_keys', 'element') ->whereJsonContains('data_values->trx_type', 'wi ...

Customize your Joi message using the .or() method

I'm attempting to personalize a message for the .or() function in Joi, similar to this: https://i.stack.imgur.com/68dKx.png The default message from Joi is as follows: Validation Error: "value" must contain at least one of [optionOne, optionTwo] ...

What could be causing the error message (No overload matches this call) to pop up when attempting to subscribe to .valueChanges() in order to retrieve data from Firestore?

Currently, I am developing an Angular application that utilizes Firebase Firestore database through the angularfire2 library. However, I am encountering a challenge. I must admit that my background is more in Java than TypeScript, so there might be some g ...

"Enhance your development experience with the TypeScript definitions for the Vue 2 plugin

Currently, I am utilizing VSCode alongside TypeScript classes for developing Vue 2 components. You can check out more information at: vuejs/vue-class-component. Within my present project, I make use of plugins like vue-i18n for handling translations of la ...

The @input field is failing to show the value entered by the user

I'm having trouble with my dynamic reactive form, as the value is not showing up <div *ngFor="let deliveryAcross of (deliveriesAcross | async)!; let i = index;"> <app-delivery-across [index]="i" [deliveryAcross]= ...

What is the best way to iterate through one level at a time?

Imagine a scenario where the structure below cannot be changed: <xml> <element name="breakfast" type="sandwich" /> <element name="lunch"> <complexType> <element name="meat" type="string" /> <element name="vegetab ...

Implement Angular backend API on Azure Cloud Platform

I successfully created a backend API that connects to SQL and is hosted on my Azure account. However, I am unsure of the steps needed to deploy this API on Azure and make it accessible so that I can connect my Angular app to its URL instead of using loca ...

Sending data from a parent scope to a directive's controller

I have a directive in my code that has a separate controller in a JavaScript file. This controller has a scope variable called parameterDatabase which needs to be populated from the calling page. I am struggling to find a way to pass a value to it. <bo ...

What steps are involved in setting up a search results page for example.com/s/keyword?

app.js app.get('/results',showResult) var express = require('express') var n = req.query.query; mysql_crawl.query('SELECT prod_name, full_price FROM `xxx` WHERE MATCH(data_index) AGAINST("'+n+'")', function(error, p ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Display the list in a grid format with 4 columns and x number of rows by utilizing Angular and Bootstrap

I need to display a list of values [1,2,3,4,5,6,7,8,9,10] as a bootstrap grid (class="col-x") using AngularJS. My goal is to create a grid with 4 columns and 3 rows from this list. Can you suggest the most efficient method to achieve this? ...

How can I display options in a react autocomplete feature?

Using the autocomplete component from @material-ui/lab/autocomplete, I am trying to retrieve the title_display result in the options field. These results are being fetched from an API using axios. You can view my code here--> https://codesandbox.io/s/r ...

The detection of my query parameters is not working as expected

Creating an Angular application that dynamically loads a different login page based on the "groupId" set in the URL is my current challenge. The approach involves sending each client a unique URL containing a specific "groupId" parameter. A template is the ...

Avoid saying the same thing more than once

Within my Typescript class, I have the following structure: class C { #fsm (...) startFoo(name: string) { this.#fsm.send('FOO', name) return this } startBar(name: string) { this.#fsm.send('BAR', name) return th ...

The art of combining Angular 6 with CSS styling for dynamic

Can we dynamically set a value in an scss file from the ts component like demonstrated below? public display: "none" | "block"; ngOnInit(): void { this.display = "none"; } ::ng-deep #clear { display: {{display}} !imp ...

What's the best way to code a loop that can accurately list the days of the month?

public class Array { public static void main(String args[]) { int[] daysInMonth = new int[31]; for (int i = 0; i < 31; i++) { System.out.println("Day of the month: " + daysInMonth[i]); } } } I understan ...

"Utilizing Firebase Functions to update information in the Firebase Realtime Database on a daily basis

Currently, I am in the process of working on a project where I aim to provide users with a daily percentage of points based on their current available points and update this data in my Firebase database. My goal is to add points for users on a day-to-day b ...

angular8StylePreprocessorSettings

I'm currently trying to implement the approach found on this tutorial in order to import scss files through stylePreprocessorOptions in Angular 8. However, I'm encountering an error stating that the file cannot be found. Any suggestions on how to ...

Transferring information between Puppeteer and a Vue JS Component

When my app's data flow starts with a backend API request that triggers a Vue component using puppeteer, is there a way to transfer that data from Backend (express) to the vue component without requiring the Vue component to make an additional backend ...