I would like to get data from a first windows and display them in console on another one in an Angular App. I can’t use cookies or local storage so I’m trying to do that via a Subject.
I created a service
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private dataSubject = new Subject<any>();
sendData(data: any) {
this.dataSubject.next(data);
}
clearData() {
this.dataSubject.next();
}
getData() {
return this.dataSubject.asObservable();
}
}
I made 2 components, one for each window.
In the first component, I have a button to send data
import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared-service.service';
@Component({
selector: 'app-page1',
templateUrl: '<button (click)="click()">Send data</button>',
styleUrls: ['./page1.component.css']
})
export class Page1Component implements OnInit{
constructor(private sharedService: SharedService) { }
ngOnInit(): void {
this.sharedService.getData().subscribe((data) => {
console.log(data)
});
}
click(){
this.sharedService.sendData('test');
}
}
In the second document, I would like to get the ‘test’ string from the first window to the console
import { Component, OnInit } from '@angular/core';
import { SharedService } from '../shared-service.service';
@Component({
selector: 'app-page2',
templateUrl: './page2.component.html',
styleUrls: ['./page2.component.css']
})
export class Page2Component implements OnInit{
constructor(private sharedService: SharedService) { }
ngOnInit() {
this.sharedService.getData().subscribe((data) => {
console.log(data)
});
}
}
I’m new with Angular. Is someone can give me some advice ? Is this the good way to do or should I do something else ?