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?

2

There are 2 answers

3
rehan meer On

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.

0
Nikhil Gaikwad On

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).