I have a service the return data model. The model contains DateTime property (RelevantDateTime) - the current UTC DateTime returned from the server. I would like to use this data in a different component than the one that executes the service. I'm using BahaviorSubject (I've used Subject and changed it to BahaviorSubject) to do so. It should be quite simple, but somehow I'm missing something - the observable is not being emmitted - the component (HeaderComponent) that required the data is not getting it. See my code:
export class MyService
{
content : any;
//I've changed the Subject to BahaviorSubject
timeOfExecutionSubject = new BahaviorSubject<Date>(new Date());
timeOfExecutionSubjectChanged : Observable<Date> = this.timeOfExecutionSubject.asObservable();
constructor (private httpClient : HttpClient){}
getData()
{
return this.httpClient.get<myModel>(<httpGetUrl>)
.pipe
.tap(
{
res => this.content = res;
this.timeOfExecutionSubject.next(content.RelevantDateTime);
}),
catchError(error => throwError(error))
);
}
getRelevantDateTime()
{
return this.timeOfExecutionSubjectChanged;
}
}
This is the component that executes the service:
export class MainComponent // This component execute the service
{
constaructor(private myService : MyService ){}
ngOnInit()
{
let sub = this.myService.getData().
subscribe (res =>
{
this.setData(res);
})
}
}
This is the compoent that requires the RelevantDataTime
export class HeaderComponent implements OnInit
{
executionDateTime : string;
constructor(private myService: MyService)
{
this.myService.getRelevantDateTime().subscribe(
result => this.executionDateTime = moment(result).format("HH:mm");
)
}
}