Skip to content Skip to sidebar Skip to footer

Observing Data Changes From Parent To Child Or Vice Versa

I have a service that I subscribe in the, let's say A component. I have a method in the A component that subscribes to the service every 5 minutes. An A component has a child compo

Solution 1:

Karan, the thing are not as you asking. Yo need'nt susbcribe to a service each time. Imagine you has a service DataService with a method getData. If you want to get this data each x seconds you can susbcribe in onInit to a timer using switchMap. To unsusbcribe I use takeWhile a variable was true, that in ngOnDestroy becomes false

 timer(0,1000).pipe(takeWhile(()=>this.alive),
                  switchMap(()=>{
                    returnthis.dataService.getData()
                  })).subscribe(res=>{
                    this.value=res;
                  })

the variable "this.value" change each 1 secons. You can pass this variable to b using input, and pass the variable from b to c using input too.

NOTE: I use the operator "of" to return an observable, in general the service becomes like

  getData()
  {
    returnthis.httpClient.get(.....)
  }

You can also has a Subject in your service, in timer of app-component send a message and subscribe to the subject as observable is c

You component A becomes like

 timer(0,1000).pipe(takeWhile(()=>this.alive),
              switchMap(()=>{
                returnthis.dataService.getData()
              })).subscribe(res=>{
                this.dataService.putMessage("I send "+res);
              })

And in component c you has

this.dataService.dataObservable.subscribe(res=>{
   this.message=res;
})

You can see an example of both cases in stackblitz

Post a Comment for "Observing Data Changes From Parent To Child Or Vice Versa"