#Signal and Behavior Subject is not working when i give the service in providers.

13 messages · Page 1 of 1 (latest)

inner lintel
#

Hi all, in below i posted the demo app, for your reference, now the problem i am having is, in First.component if i give the service in providers, the signal / behaviorSubject is not working i means i am not getting value, when the signal value is updated and behaviorSubject value is also updated, but when i remove it. it's working, i am just curious what is happening when i give the Service in providers, is this because i created component dynamically or any DI concept involves, i am sure it's about DI, but don't know what concept,

https://stackblitz.com/edit/angular-ywujral6?file=src%2Ffirst.component.ts

A angular-cli project based on @angular/animations, @angular/common, @angular/compiler, @angular/core, @angular/forms, @angular/platform-browser, @angular/platform-browser-dynamic, @angular/router, core-js, rxjs, tslib and zone.js.

stiff flower
#

What exactly is not working in your example? I am getting the following console log if I first press "Load Component" and then "Second Component Button":

res from behaviorSubject null

Inside Effect

Emitting...

res from behaviorSubject Hello

Emitted...

Inside Effect

effect inside

this is exactly what would be expected, no?

inner lintel
#

Can you uncomment the providers array in first.component.ts file? reload and check again?

stiff flower
#

Well, yes, if you add that you now have two instances of SharedService. One in root, which is used by SecondComponent and one scoped to FirstComponent, which is only used there (because FirstComponent has no nested components).

#

SecondComponent uses the BehaviorSubject and Signal in the root instance of SharedService.

#

FirstComponent subscribes to and uses the signal from its own instance.

inner lintel
#

ohh so the problem is SharedService have two instance? got it thank you!

#

SO the SIgnal and BehaviorSubject are tied with DI concepts?

#

i thought those are act alone on their own

stiff flower
#

Not really, no.
It's just that you have two instances of the service and the service creates a new Signal and new BehaviorSubject. So every time you do new SharedService you also get a new BehaviorSubject and a new signal.

#

And

providers: [ SharedService ]

is just a short form.
Long form:

providers: [
  { provide: SharedService, useClass: SharedService }
]

or, to make it even more explicit:

providers: [
  { provide: SharedService, useFactory: () => new SharedService() }
]
#

So: Every time FirstComponent is rendered, it first creates a new instance of SharedService for itself to use. And that service then does new BehaviorSubject, which is a new BehaviorSubject and it does signal(...), which is a new signal.

#

Makes sense?