0

I have a form which accepts an input and that input will be used by my API to retrieve the data. As per angular, I can use @input or Behavioural subject for sharing this value with child components or unrelated components.

Since my input will be one time activity, why cant I use a service with a private variable to share it with different components rather than using @input and Behavioural subject ?

What I'm saying is:

In the template:

<html>
  <body>

    EmployeeID <input type="text">

    <button type="submit" (click) ="onsubmit()>Submit</button>

  </body>
</html>

In component:

onsubmit() {
  this.myservice.addData(inputValue)
}     

And in the service:

private myinput    

addData(input){
  this.myinput.add(input)
}

And this is jus a rough code and not actual one..

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93
NewBee
  • 207
  • 2
  • 5
  • 11
  • Who said you can't do that? IMO it would be against good practices but that code is pretty valid. – Mateusz Witkowski Oct 03 '18 at 14:45
  • @MateuszWitkowski so when exactly we have to use Behavioursubject.. what is the correct use case ? And if u mean the best practice.. where i can find more details on that.. – NewBee Oct 03 '18 at 14:50
  • You would use a BehaviorSubject When there is a chance that the value changes and your downstream component needs to be notified about that change. – Henry Oct 03 '18 at 14:53
  • Behavioural Subject explained here: [behaviorsubject-vs-observable](https://stackoverflow.com/questions/39494058/behaviorsubject-vs-observable) – HDJEMAI Oct 03 '18 at 14:54

1 Answers1

2

Well, sure you can...sort of. Private variables are only accessible inside of their own class, so it'd have to be a public variable.

However, you'd lose the main benefit of the BehaviorSubject. If the value is being shared with multiple components, the benefit of having a Subject is that those subscribers will be updated asynchronously with that value when that value is set. Otherwise, those components would have to null check that value instead of simply receiving it reactively. Those components would also receive updates to that value reactively, so if that value is being updated instead of remaining static, a BehaviorSubject becomes far more useful.

Another note is that having values as BehaviorSubjects or even private BehaviorSubjects on a service with asObservable getters is a design pattern commonly seen in 'stores', or stateful services made popular by libraries like @ngrx/store.

Angular is a heavily reactive program built on RxJS, but at the end of the day, using Observables in your app is still a design choice.

Also, with simply having a shared variable, it's usually best practice to make that value immutable from outside the service -- either by writing only a getter for that value, or by keeping it private and having it only accessible through methods.

joh04667
  • 7,159
  • 27
  • 34