0

I want to pass the data from one component to another component using Subject. I am using Angular 7. Below is my service: -

public shareData = new Subject();
setShareDataOfReadingDetail(datatobeShared:any){
    console.log(datatobeShared)
    this.shareData.next(datatobeShared);
    this.shareData.complete()

  }

  getShareDataOfReadingDetail(){

    return this.shareData.asObservable();
  }

My first component is : -

shareDetail(detail){
    this.readingService.setShareDataOfReadingDetail(detail)
    this.router.navigate(['./tabs/tabs/readings/detail'])
  }

And the component in which I am getting the data is : -


  ngOnInit() {

    this.readingService.getShareDataOfReadingDetail().subscribe((data)=>{console.log(data)})

  }

But the subscribe for subject is not triggering at all (i.e it is not printing anything in the console)

Daniel Piñeiro
  • 3,009
  • 1
  • 16
  • 26
ShubhamVohra
  • 107
  • 1
  • 2
  • 10
  • 1
    You immediately `complete()` your `Subject` in `setShareDataOfReadingDetail()`. If I remember correctly, you need to use a [`BehaviorSubject`](https://stackoverflow.com/questions/39494058/behaviorsubject-vs-observable) instead to replay your last value. – alex kucksdorf Apr 30 '19 at 10:42
  • @alexkucksdorf I have used BehaviourSubject also. It is also not triggering – ShubhamVohra Apr 30 '19 at 10:48
  • @alexkucksdorf It worked fine using BehaviourSubject and removing complete sentence. Thank you very much – ShubhamVohra Apr 30 '19 at 10:52

1 Answers1

0

When do you instantiate the second component? Before or after the call to shareDetail? I'm assuming it is as a result of the router navigation. If so, you are sending a value and completing the Subject before the details component gets a chance to subscribe to it. I would hold off completion of the Subject until later, probably in the ngOnDestroy of the service.

I would also consider using a BehaviorSubject or a ReplaySubject, as well (to provide caching of the value).

night_owl
  • 856
  • 6
  • 12