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