Angular 5 update view on provider changes by RXJS

Hi All, in angular version 1 and it’s subs, we have a definition called services which are able to share a data between two or more than two different controllers, once a data changes happening inside that service data structure, angular would run the $digest mechanism to apply that change on all of the variables which referenced to that data and then update the view. kinda like this. easy isn’t it. but thing got changed in angular two and other versions after version two, ReActive programming is concept which has been introduce mostly in angular by RXJS and therefore there is no such mechanism to do the same for you.

assuming that you have a little information about RXJS, and If you don’t , go get it.
so as I explained and since there is not any service in angular 5 anymore, what we should do?
simple, in new angular version we have providers which can plays the same role for us, but it’s different little, so instead of service we are going to have inject-able provider.
let’s make it clear by an example. we have two different component which inside each we are showing some common values to user and both of these components are getting this value from a provider. once the provider value updates, the components value should update as well.
in angular 1, it would happening just by simple JavaScript reference, you may try the same but that will not work  since angular view update strategy is changed, but we can do this by help of RXJS and it’s observables.
assume we have “component1.ts” & “component2.ts” & “userProvider.ts” like below;

Component number 1

Component number 2

User provider

so what’s just happened is, inside the provider, we defined “newUserSubject ” variable as “Subject”; whch can play both roles, data consumer and data provide.

What is a Subject? An RxJS Subject is a special type of Observable that allows values to be multicasted to many Observers. While plain Observables are unicast (each subscribed Observer owns an independent execution of the Observable), Subjects are multicast.”

now we can subscriber to this variable or broadcast the data manually (like out example) or use it as consumer of other observable. I mean as an Observer.
inside the the constructor of this provider, we are broadcasting some data manually, and same thing will happen whenever we call “setUserData” function and as we subscriber to this observable in each components, once a data get changed, it will reflect on both places. So here it’s is in basic mode, But if you have large application and you want shared data service across, you need to dig into deep and bring scale-able structure to keep the performance good, and development easier.
Any question? leave a comment.

 

 

 

Leave A Comment?