0

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");
            )
        }
    }

Dharman
  • 30,962
  • 25
  • 85
  • 135
Guy E
  • 1,775
  • 2
  • 27
  • 55

1 Answers1

1

Found the root cause for the observable not being emitted - The service should have declared in the most "upper" module or in a module that include the modules of the 2 involved components. In my case - I removed the declaration of MyService from the module which the MainComponent was included in, and removed it to be declared in the module of the Header (which imports the mainComponent module). See reference in: https://github.com/angular/angular/issues/11618 -
"In order two share a service between multiple components, you should provide the service at a level higher and not add the service to the providers of both components."

Guy E
  • 1,775
  • 2
  • 27
  • 55