3

Angular 8 provides us rxjs library , we can use subject from that library to set data that can be used gloabally in our application by declaring it in service file and this same we can do is by declaring just a variable in service file and using it globally in our application . Is there any benefits using subject over a variable in this case?

prince
  • 31
  • 4

2 Answers2

1

if the data you want to use globally will remain constant (ex:apiURL or siteTitle), then its better to go with a global variable declaration. else preferred way of communication between unrelated components in angular is through subjects, as subjects are observable. Ref: https://angular.io/guide/observables. If yes, consider accepting the answer. comment down if any queries. Thanks.

Dharman
  • 30,962
  • 25
  • 85
  • 135
rehan meer
  • 28
  • 7
  • The question is about the benefits of using a subject. Saying "it's preferred" is both opionated and not answering the question. – Ingo Bürk Oct 06 '20 at 07:56
  • using obserables will just increase my length of code if i use variable it very less code to do jst declare the variable, if there is no performance benefits then why would anyone go for subjects(rxjs). – prince Oct 06 '20 at 08:21
  • In a scenario, when another component needs to be notified of this variable change, you can use BehaviourSubject which would actually store the value and notify its subscribers of the change. If its just constant value, you may very well keep it as a static constant. – Haroon Oct 06 '20 at 10:25
0

Suppose you have a variable:any in service that is used at multiple components & when variables value is updated. So here you will need to check everytime whether the value is updated or not (Pull based approach).

But if you use variable:Subject<any>, then you can subscribe to that variable & whenever the variable's values is updated, updated value gets emitted to listener (Push based approach).