My Angular application has the following components.
1 MessengerService. This service I am using to send/get data to other components using RxJs. The code of the service is here.
import { Injectable } from '@angular/core'; import {ReplaySubject, Subject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class MessengerService {
_Subject = new ReplaySubject(1);
constructor() { }
SendMessageWithData(MessageAndData){
this._Subject.next(MessageAndData);
}
GetMessageWithData(){
return this._Subject.asObservable();
}
}
2 ProductComponent. It has a button with a function and its snippet is here.
SendProductId(_ProductId){
this._MessengerService.SendMessageWithData({ //Sending data to the Messenger Service
id:_ProductId,
Component:'ProductComponent'
});
this._Router.navigate(['viewProduct']); //Then routing to the viewProduct Component
}
3 My Last Component viewProduct Component Here I am getting the data from ProductCompoent using my MessengerService in ngOnInit(): void {} the snippet is following.
ngOnInit(): void {
this._MessengerService.GetMessageWithData().subscribe();
// some code here
}
Now coming to my question. When I route to viewProduct from ProductComponent function. it send the data and then in ngOnInit() the GetMessageWithData() work perfectly. But when I reload the viewComponent the function this._MessengerService.GetMessageWithData().subscribe(); in ngOnInit() do not run and the code inside it do not run. Please guide me how to fix this problem.