Tips on storing and retrieving data between pages in Ionic 4/5: Saving data to a service and accessing it from a

Looking for assistance from the community

I am trying to pass data between pages using a service in Angular.

Here is the code for the parent component.ts file:

import { Component } from '@angular/core';
import { ShareService } from '../share.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  message:string = 'I am from home.ts';

  constructor(private shareSvc: ShareService) {}

  ngOnInit() {
    this.shareSvc.sharedMessage.subscribe(message => this.message = message)
  }

}

Below is the service code:

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

@Injectable({
  providedIn: 'root'
})
export class ShareService {
  private message = new BehaviorSubject<any>(null);
  sharedMessage = this.message.asObservable();

  constructor() { }

  nextMessage(message: string) {
    this.message.next(message)
  }
}

Lastly, this is the code for the component that will display the data received from the home/service:

import { Component, OnInit } from '@angular/core';
import { ShareService } from '../share.service';

@Component({
  selector: 'app-pagina2',
  templateUrl: './pagina2.page.html',
  styleUrls: ['./pagina2.page.scss'],
})
export class Pagina2Page implements OnInit {

  message:string;

  constructor(private shareSvc: ShareService) { }

  ngOnInit() {
    this.shareSvc.sharedMessage.subscribe(message => {
      this.message = message;
      console.log(this.message);
    });
  }

}

If needed, I can also provide the page2 HTML code:

<ion-header>
  <ion-toolbar>
    <ion-title>pagina2</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <h1>Message from Service and Home: {{message}}</h1>
</ion-content>

Here is the resulting output image for reference: enter image description here

Answer №1

It appears that there are two issues causing you not to see any of your messages

  1. The first issue is that your first message ("I am from home.ts") is emitted before you subscribe to an observable, leading to it not being received
  2. While your second message emitting and subscribing is done correctly, you are missing the step of actually calling the newMessage method, resulting in the second message not being received.

Please take a look at this small demonstrating example to see a visual representation of the issues mentioned.

P.S. Your code could be simplified by using the async pipe and eliminating the unnecessary transformation of BehaviorSubject to a simple Observable. Check out the example here.

Update

You mentioned wanting something similar to this: 112bsimtvcd2kuxvj2ww2jkd-wpengine.netdna-ssl.com/wp-content/…, but specifically for communication between sibling components using 3 components (Home.ts, Page2.ts, and Service)

If that's the case, your solution can be implemented as shown here. Simply inject your service into all necessary components and utilize its method for sending messages as well as its message property for subscribing to incoming messages.

Answer №2

If you're experiencing issues with the template loading without the message from the service, try calling the newMessage function on page initialization or assigning it to a click event.

<ion-header>
  <ion-toolbar>
    <ion-title>pagina2</ion-title>
  </ion-toolbar>
</ion-header>

<ion-content *ngIf="message">
  <h1>Message from Service and Home : {{message}}</h1>
</ion-content>

 **pagina.ts**

    ngOnInit() {
    this.shareVc.sharedMessage.subscribe(message => {
      this.message = message;
    });
    this.newMessage();
  }

  newMessage() {
    this.shareVc.nextMessage('I am from page 2');
  }

Answer №3

In lieu of keeping the behaviorSubject as private, it is advised to make it public.

public message = new BehaviorSubject({});

Subsequently, you can utilize message.next(value); from any part of your application by importing the service.

It is possible to subscribe to this using message.subscribe(), retrieve a one-time value with message.getValue(), or employ the async pipe in HTML.

The line

sharedMessage = this.message.asObservable();
is unnecessary.

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 encountered a TS error warning about a possible null value, despite already confirming that the value

In line 5 of the script, TypeScript raises an issue regarding the possibility of gameInstanceContext.gameInstance being null. Interestingly, this concern is not present in line 3. Given that I have verified its existence on line 1, it is perplexing as to w ...

Issue with resizing Ionic carousel when making an $http request

In my Ionic project, I am utilizing a plugin to create a carousel (https://github.com/ksachdeva/angular-swiper). The demo of this plugin includes a simple repeat function. However, when I replaced the default repeat with my own using $http, it caused an is ...

Error occurs when trying to open a modal popup within a component due to changes in expression

In my application, I am facing an issue where I have a parent component passing HTML content to a child common component using @ViewChild(). However, when the Child component loads up a popup, the console throws the following error: "ExpressionChangedAft ...

Ensuring Function Parameter Usage in Typescript and Angular 5

Currently, I am developing a component using Angular 5 and Ionic 4. My objective is to include a Refresher event to hide the refresh spinner whenever the user triggers the final function to conceal the spinner. Provided below is an excerpt of my code: e ...

The function successfully triggers when clicked using (React, JS, TS) but does not respond to key presses

When the function is called with "onClick", it works correctly, but when called with "onKeyPress", it does not execute an if statement. scenario Consider a scenario where you can search for food recipes (e.g. "pizza") and receive a list of recipes from a ...

Encountering a JSON error while attempting to login through an API on the Ionic platform

While implementing the login functionality through API in Ionic, I encountered the following error: Error: Property 'json' does not exist on type '{}'. Below is my loginpage.html code: <ion-header> <ion-navbar> & ...

What is the method for choosing an element by class name in TypeScript?

Currently, I'm working on creating a responsive menu bar that collapses on smaller screens. The challenge I'm facing is that I'm using TypeScript for this project. Is there any guidance on how to translate the following code into TypeScript? ...

What could be causing my cypress tests to crash because of the pluginsFile?

Encountering an issue with Cypress and TypeScript on a project. Setting up Cypress with TypeScript in a new project works fine, but when attempting the same process in a larger project, there's an error upon running cypress causing the browser to cras ...

Using Angular 4's ngComponentOutlet to showcase ContentChildren that are dynamically changing

My main objective is to create a unique container component with a dynamic list of customized card components that can be accessed individually (instead of as a group using ng-content). <custom-card-holder> <custom-card></custom-card> ...

React-query v5 - Updating or fetching outdated query

I am currently using the Tanstack/react-query v5.12.2 library and I am facing an issue with invalidating or refetching an inactive query using the useQueryClient() function. It seems that something has changed in version 5 of the library. I have tried sett ...

Tips for eliminating the undefined/null values from an array nested within another array in Angular

DATA = [{ application: [{ name: 'Room1' },{ name: 'Room2' },{ name: 'Room3' },{ name: 'Room4' },{ name: 'Room5' }], name: 'Batch 1&ap ...

Concealing a navigation tab with Angular4 in Typescript: A tutorial

I have successfully implemented 3 tabs in my Angular 4 project. At the moment, I am focusing on working with the first two tabs and planning to tackle the third tab in the near future. To keep things clean and organized, I am looking to use JavaScript/Typ ...

Can you explain the significance of the syntax #foo="myFoo" used in this template?

I grasp the concept of the hashtag syntax <input #myinput > which gives a name for element access, but I'm puzzled by the similar syntax used in an example on the angular material website: <mat-menu #menu="matMenu"> What does t ...

Create objects in the gallery

I recently developed a React Material-UI component using Typescript: <Grid container direction="row" justifyContent="flex-start" alignItems="flex-start"> <Grid item xs={5}> <B ...

Playwright script encounters module not found error

I am currently facing an issue with implementing Playwright in my project. It seems that Playwright is struggling to a) resolve path aliases and b) it is unable to locate certain npm packages that have been installed. Here is the structure of my project: ...

I can't figure out why I'm receiving undefined even though all the variables are populated with the necessary

I have been working on a project that involves implementing email and password authentication using Firebase. However, I encountered an error when the user submits their credentials: FirebaseError: Firebase: Error (auth/admin-restricted-operation). at ...

The reactivity of arrays in Vue components' props is limited

I've got an array with component data that I'm attempting to render using v-for <div :style="style" class="editor-component" v-for="(component, index) in components"> <Component :is="component.name" v-bind="component.o ...

Unable to view loggly-winston debug logs on the user interface

I am having an issue where I cannot see any logs when calling winston.debug. It seems like the log level allowed to be seen needs to be changed. For more information, refer to the winston documentation or the Loggly node.js documentation. To start, instal ...

What is the best way to refresh an array in a different component?

It all starts with a data response object: let response = { attachments: [{id: 1}, {id: 2}, {id: 3}] } This valuable data is utilized in the root component <app-root></app-root> <app-documents [response]="response"></app- ...

Is it possible to use non-numeric values as keys in a Typescript Map?

During a lesson: private items: Map<number, string> = new Map(); ... this.items[aNumber] = "hello"; Results in this error message: An element has an any type because the expression of type number cannot be used to index type Map<numbe ...