Angular2 flush services data - javascript

I have an Angular2 app where user can log in and log out and I need to flush services data on log out, because they hold some data and backend subscriptions (websocket). Currently the only way I found is to reload the page after log out, but it's a crunchy solution. So, is there some convenient way to reinstantiate services (or remove the data they hold) in Angular2?

How about moving all your initialization logic to a method of that service, i.e init() then call that from the constructor when the application starts or on user logout.

Related

Reactive approach + Subject service in angular

iam trying to use reactive approach in my angular app, but i am not quiet sure, that i am using it correctly. So i have a few questions to clarify it.
In my app i have global status service(its subject service), which holds some basic state of the app - month and workload id selected by user(user can switch it in navbar).
On market page i display offers, which user can apply for. To get data i need, iam using observables from market service with async pipe - no manual subscription.
Here is part of market service:
export class MarketService {
//subject with updates
private prefChangesSubj=new Subject<MarketOffer>();
//observable which loads data from API, everytime user changes status.
get loadedEvents(){
return this.statusService.appStatus.pipe(
switchMap(status=>this.getOffers(status.selectedMonth)),
shareReplay({refCount:true}));
}
//observable consumed by component - loaded Events + changes made by user
get events(){
return this.loadedEvents.pipe(
switchMap(initEvents=>this.prefChangesSubj.asObservable().pipe(
startWith(initEvents),
scan((events:{offers:MarketOffer[],dayPrefs:MarketOffer[],month:Date},update:MarketOffer)=>{
....
return events;
}
}
getOffers(date:Date){
return this.httpClient.get(....);
}
And now my questions:
Is it Ok, to have these combined observables(loadedEvents, events) in service? Or they should be combined in component?
How to handle errors when iam using async pipe? For example in loadedEvents getter, iam using switchmap to call getOffers, which gets data from API. How to handle error if http call fails? I can use catchError, but than component wouldnt be notified about error. But i must catch this potential error cause otherwise it will break the whole observable and new data wont be loaded later. How to solve this problem?
Is the approach to create combined observable from loadedEvents and changes subject correct? Or how it should be done using reactive approach?
I have searched for articles on this topic, but most of them doesnt cover problems like error handling. So i would be grateful even for links to some good articles or example apps, so i can read more about this.
thx and sorry for long post :)

Where to place init code with Angular 1?

I have an angular web application that is currently calling the backend API every time I need to display the user name or user image. However, I would now like to be able to cache this information in localStorage when the application is first started. What would be the best way or best place to do this in Angular? I image it would be something equivalent to the jquery $(document).ready method. Any hints would be appreciated.
You could put it in the run block. This will run once when your app starts up
angular.module('myApp').run(function () {
//Run init code
});
While you can use module.run for this, a better option would be a thematically related service. Angular services are created once, and so you can just put your loading code on the top level.
E.g.
angular.module('myApp').service('currentUser', function() {
// load user data from local storage, if not found load from server
// then store in localStorage
this.name = /* loaded name */;
// etc...
});
Note that most of requests are asynchronous, so you might want to do a factory that would return a user promise instead.

Structuring calls to update global and local state

Some of my components doesn't want to store all state globally. Two examples:
messages component: usermessages are fetched and stored locally because they are only needed for the current component. But when they could not be fetched (api error), the error should be dispatched to global state (vuex).
buy component: 'recent buys' are fetched and stored locally, but 'money' should be dispatched to global state, and error too when recent buys could not be fetched.
I'm currently figuring out how to structure this and I need some help. I have a directory services which includes calls to my api. Let's take the buy service as an example:
/services/buy.js:
// here code to dispatch money state
// here code to dispatch 'last activity' state
Vue.$http.get('/buy', credentials)
.then((response) => {
// return recent buys
})
.catch((error) => {
// here code to dispatch error state
});
There are some logics between the services as well: For example, after a succesful buy, a new message should be sent from /services/newMessage.js
But how and where should I structure all of this? Let's take the buy component as an example. I see a couple of options:
#1: This is the code above
The buy-component imports the buy service and calls it: newBuy()
The service dispatches the money to global store, and the service gets the recent buys and returns them
Back in the component, it updates the local store with the returned value from the service
The component has the logic too: after a succesful return, it calls the message service to send a new message: sendMessage()
#2: The difference with #1 is that the logic takes place inside the service
The component imports the buy service and calls it: newBuy()
The service dispatches the money to global store, and imports the message service
The message service sends a new message: sendMessage()
Back to the buy service, the recent buys are fetched and returned.
The component now updates the local store with the returned value
#3: The difference with steps above is that all actions related to Vuex are inside a special actions.js file, so it is a clear separation of global and local state updates.
The component imports the buy service and calls it: newBuy()
The service imports ./store/actions.js and calls the updateMoney() service which updates the money
Goes further with the steps from #1 or #2
Could someone please help me out? How to combine components that use both global and local state? Are one of the three steps above the right way to do that?
In short, based on your situation: option 2
For me if there is no need for a state to be shared globally then all you are doing is polluting vuex's states by writing everything to it.
If for instance you had 10 components that functioned like the buy component, and each of those pulled an individual state only they needed from your vuex store, then you will be making the vuex store harder to reason about.
Furthermore if you start attaching actions and mutations for those states, then you'll likely need to build modules for each of the 10 components, again obscuring your state and logic.
Therefore in this instance option 2 seems a far better way to go if you are sure you won't need the state you retrieve elsewhere. You seem to have a pretty good grasp on why you would use vuex so that puts you in good stead. I would say that half the work with larger applications is in the planning. Therefore if you can map out how your app will function and see before you build where the connections need to be, and in turn where a components data is completely isolated, you should be able to quickly make those decisions on what you do and don't push to vuex.
In terms of the choice between option 1 & 2 I would say this again comes down to a question of scope and keeping things DRY. If every time you are returned data from newBuy you have to call sendMessage and you have the data in buy-service to populate the message, then your services should work together. It's fine that they do so, after all you are no doubt writing the message-service in a manner that decouples it from any dependancies outside those for sending messages. Therefore if the buy-service is written in a similar fashion it can pull that in and utilise it.
With the above in mind Option 1 therefore appears to be duplicating a function which would need to be run every time the buy service is called. For that reason I would avoid it in case in the future you want to expand things, as your app should be far easier to reason about if dependant functions are not replicated in various places. Instead you would look at newBuy and see on it receiving its data, it calls sendMessage and therefore updating is simple and the logic is clear.
To provide a little more context, I'd look to run the various stages like below:
The component imports the buy service and calls: newBuy()
Calling newBuy() should return a Promise to the component
The buy service imports the message service
The buy service fetches the data, i.e. newBuy calls getMoney and getRecentBuys.
Both of the above return a Promise, now you use Promise.all to wait for the 2 endpoints to resolve and pass back their data.
On resolving of the newBuy Promise.all:
getMoney returned data: the buy service dispatches the money to vuex modules store
The money store could be held within a vuex module if you have various types of data within this store. It would help make its state, actions etc.. easier to work with
The buy service calls the message service to send a new message: sendMessage()
The buy service resolves its Promise
pass the recent buys as the payload
Promise is resolved on the component which now updates its local data with the payload
On rejecting of the newBuy Promise.all:
The buy service rejects its Promise
pass an empty payload or message
dispatch error to vuex store
Promise is rejected on the component so component knows not to update its local data

Angular - initiate a response when data loads/changes

Relative Angular newbie here, and I am wrestling with what would seem like something most applications need:
Watching a model/data and doing something when that model is hydrated and/or has a state change.
Use case would be, when a user logs in (user model gets initiated) a complimentary directive/controller sees the state change, and then requests out to the backend to get a list of this users corresponding data elements (ie Notifications, emails, friends, etc)
Ive parsed through StackOverflow and such, and it always appears that a shared service is the way to go, however I never find a definitive answer about how the directives are to watch the state change. Some suggest a broadcast/watch while others say that is a bad pattern.
Our app currently does employ a shared UserService, which contains model representation of a User (data and simple methods is fullName())
This service also has a subscription hook that directives can subscribe to
onLogin: (fn) ->
$rootScope.$on userService::login, fn
and the use is:
UserService.onLoad(myFunction)
When the UserService loads the User, it then broadcasts userService::login and all the listeners are run. Hence everyone that shares the UserService can subscribe and respond to a User logging in.
This all works. But I was thinking there must be a built in Angular way that the directives can just know about the state change and then do myFunction (ie make additional data calls)
Thoughts and feeling would be extremely appreciated!

Angular JS Service Architecture

EDIT
The short version:
Say I have application data is many different services. How do I get around needing to inject all of those services into every controller that displays application state?
EDIT
I am building my first Angular application. The basic design is I have a home page that shows the value of about 5 different variables (which are each pretty complicated). While on this page the app is collecting and analyzing data from bluetooth. Occasionally, the these 5 variables and some bluetooth data are saved to a REST back end and also saved to the device. There are pages for each of these 5 variables to change their value.
I have done my best to follow best practices. I have very thin controllers. I use services for all my data. I really only use $scope for binding data between views and controllers.
My issue now is that I started with a global "State" service to keep track of those 5 variables. I inject into any controller that needs to display state, and bind the html to it. Any time I want to change any state, I call a method of that State service to do it. This worked well, but now that State service is getting huge.
I have tried to break functions out to other services, but I run into the issue of needing to read data from the State service, then writing back to other properties of the State service. If I inject the other service into State, I can't inject State into the other service too.
I have thought about how I could have many smaller services, but I keep coming back to when I save the data to the server. When I do that I need to gather up data from every corner of the application to send up. If all this information is stored in different services, I am left with injecting all of them into a single service once again.
As I write this, I am pretty sure I am missing a big concept with using $scope across an application.
Any pointers would be appreciated,
Thanks,
Scott
Could you divide things into sub-services, and then make the State service an aggregator for these sub-services, then instead of injecting State into the sub-services, you inject the specific sub-service that you need? E.g.:
var app = angular.module('services', []);
app.service('sub1', function(){
return {
// ...
}
});
app.service('sub2', function(sub1){
var data = sub1.getData();
data.prop = 'new_value';
sub1.setData(data);
return {
// ...
}
});
app.service('State', function(sub1, sub2){
var data = sub1.getData();
data.prop = 'new_value';
sub1.setData(data);
var data = sub2.getData();
data.prop = 'new_value';
sub2.setData(data);
return {
// ...
}
});
Looks like you need Redux to help you manage your application state
https://github.com/wbuchwalter/ng-redux

Categories

Resources