Angular services decoupling - javascript

I'm playing with angularjs doing some simple stuff. I wanted to incorporate some real time messaging like PubNub, PubSub or Pusher.
Basically I have it working, but it seems too cumbersome in some areas. Maybe you can show me a better way.
Ok, so here is my working jsfiddle (with pubsub faked) http://jsfiddle.net/canree/dD5VR/
I have external service (pubsub) and created angular service for it.
Now as I don't want other parts of my app to be dependent on this concrete implementation , I decided to create another one (inbox) that would store all the messages pubsub sent. And this inbox would be the dependency across my app (instead of pubsub).
So I want my dependencies to be:
controller -> inbox -> pubsub
When pubsub receives a message it needs to add it to inbox so that controller can see it and react accordingly. The problem is I don't want this backward dependency (pubsub -> inbox). I'd like pubsub to notify observers that message was received.
What I have now is ugly callback registration (inbox registers callback in pubsub). I don't like it very much as it has a lot of boilerplate (regarding this handling etc).
I wonder if there is other way to connect those services? Events (but without being forced to use $rootScope everywhere)? If so, where to register such event handler? Can services receive events?
Take a look at the fiddle provided and advice me how to solve it better way.

I don't want other parts of my app to be dependent on this concrete implementation
The interaction with the server is already wrapped/abstracted in the pubsub service. If the interaction with the server needs to change, it is already isolated to that service. I don't think adding another layer of abstraction buys you enough to offset the extra code you need to write (as you've already seen).
Here are a few other observations about how you could simplify your code (some of this you probably already know, but it might be instructive for others):
The content() function is not necessary (especially since messages is not private data). In Angular the controller $scope/model is often directly tied to a service model, so you could simply use:
$scope.messages = inbox.messages;
(If you like the content() function, consider making messages private in the inbox service.)
There is no need to send an event to the inbox controller about the change to inbox's messages array. The append() function just needs to call $rootScope.$digest(). And actually, this is probably not needed, since the real service would likely be using $http or $resource, which will automatically call $apply() or $digest. So _broadcastNewMessage() is not needed, nor is the $scope.$on() in the controller.
Even if you leave the content() function as is, you still won't need to broadcast anything.
Since inbox is dependent on pubsub, I would have the inbox service register itself
pubsub.subscribe(this.append, this);
pubsub's init() method can be in-line (no function required)
Fiddle with all of the above observations incorporated.
I wonder if there is other way to connect those services?
I can only think of model sharing (e.g., in service1: this.service1_obj_or_obj_property = service2.service2_obj_or_obj_property) and creating functions on the dependent service that the other service can call.
Can services receive events?
Since $on and $broadcast are defined on Scope, and since services are singletons and are not affected by scopes, I'm pretty sure the answer is "no."

Related

Angular 7: How to send and receive a global event?

I study angular, sorry for the stupid question.
I need to make a service for windows with a single instance of the service or be able to send broadcast events and listen to them in each component.
Using #input and #output is not like There is a different nesting of components.
How to solve this issue?
One way to implement this is to use a service for that.
Inside the service create an Subject member variable (you need RxJS for it, which angular already installed because it's a dependency).
The Subject can be subscribed by any component outside the service (you'll need to inject the service in the component constructor).
Then, whenever you want to trigger that event you call .next() on the Subject and each subscriber will activate its own callback.
When subscription is done and not needed anymore it's important to .unsubscribe() from the Subject, otherwise there's a risk of memory leak (since the subscriber does not unsubscribe itself).
There are many examples out there, here is simple one.

Update the DOM based on click event using service

I'm trying to update the DOM based on a click event, by using a service.
Specifically, I'm trying to use bootstrap's alerts to alert the user when they click on a particular button on the page. I'd like to be able to call notify.createNotification("Saved successfully") for instance, to tell the user that they have saved successfully.
I'm using ui-router and have managed to abstract the notification to a (isolate scope) directive and the accompanying template. The notification currently shows, updated, at the head of my application (all other views inherit this view) upon $scope.createNotification() (from within the click event). This works because the child views inherit the $scope property. Clearly though this pollution and abuse of the inheritance of the $scope is not ideal, hence I'd like to move it all into a service.
I've got as far as trying to use a factory to update the notification object, which contains state information for the alert, i.e. display:true/false, text etc. The trouble with the factory is it just returns where it's called from, I need to be able to update the parent.
...I feel I've done 9/10ths of the work on this, but that last 1/10th is really puzzling me.
Any help would be greatly appreciated.
Note: Guess I'm also looking for a 'best practices' here too, I mean $scope pollution works, but it's far from ideal. Thanks
This could be solved using pub/sub approach.
Create NotificationService that is used to send notifications. For callers it would look like NotificationService.alert({text: '..', ...})
Create <notification-area> component that subscribes to NotificationSerivce and displays notifications sent from anywhere.
NotificationService itself should implement pub/sub interface. Use any implementation of EventEmitter (like this one) or even angular.element to provide on(), off(), trigger() methods.

Angular Project Architecture

I am building an app in angular, which consumes different APIs and Gives options for the user to select it will be recorded and sent back to the server.
I have designed it as follows.
All the common logic in Main Controller and all other options in different controllers as the child of main controller.
Main Controller retrieve all the data that are required to run the app.
which is consumed by all other child controllers.
To make sure data is loaded I am using promise attached to scope. So all the child controller will know data loaded.
I have moved data updation part of all child controllers to main controller
because all the updates happen in one object.
Child Controller emit/broadcast to communicate between child and main. So when update happens child will emit an event with data which will be captured by Main and it will do the update.
MainController {
$scope.loaded = DataService.get();
$scope.userOptions = {};
$scope.$on('update',function(){
updateUserOptions();
})
}
ChildController {
$scope.loaded.then(function(){
//all logic of child controller
}
$scope.onselect = function(){
$scope.$emit('update',data);
}
}
Questions
Is it a good practice to use events between controllers ?
is it good to use promise attached to scope for child controllers ?
Will it improve my code if I start using services ?
I will try to answer your question based on my own experience. Recently I've built a single page application and I've refactored its architecture.
Here are my answers:
Is it a good practice to use events between controllers? IMHO, it is the most flexible way to share information between all controllers even if they have isolated scope (using $broadcast or $emit for example). This is called the Observer design pattern. However, you can use services instead of events to share data between them. If you are going to use $rootScope, be careful as all the $scopes inherit from $rootScope.
is it good to use promise attached to scope for child controllers ? Firstly, you have to learn about how scope inheritance works. You have to take care to avoid property shadow in JS. Secondly, I would move out all the logic from scope.loaded in ChildController to a service such as ChildService. Keeping the business logic (such as request, etc) in Services instead of Controllers, will ensure it can be re-used.
Segregation of business logic is good design principle.
Will it improve my code if I start using services ? I answered this question above.
In addition, in order to build a good architecture I've read this angular style guide written by John Papa.
I recommend the following changes:
To make sure data is loaded I am using promise attached to scope. So all the child controller will know data loaded.. Instead I would emit a custom 'loaded' event in the MainController using $scope.$emit('loaded'). After that, in the ChildController I would use $scope.$on('loaded', function(){}) to handle the event.
I would move the updateUserOptions function to a service and inject the it into just the controllers that need it.
I hope that helps!
Is it a good practice to use events between controllers ? Not as the main form of data sharing, but you can use it to notify about system events, such as data ready.
Is it good to use promise attached to scope for child controllers ? Don't use scope inheritance, it causes lots of annoying problems.
Will it improve my code if I start using services ? Yep.
This is what I would do in your place:
dataService - this service is responsible for all data coming in / going out. Whenever a request for data is made (no matter which controller asked for the data), the service caches the data (save the promise is good enough). All further requests get the cached data unless they specify they want a fresh data. Whenever data is updated (1st time or refresh), the service broadcasts a 'dataReady' event via $rootScope to which the main controller and other subscribers can listen.
The service is also responsible for data updates, and when the data is updated you can also broadcast an event via the $rootScope.
When the event is activated, all subscribers query the service, and get the data they need.
Controllers - avoid controllers, use directives with isolated scope, and pass the data between them using attributes. In this way you can be sure that each directive gets what it needs, and not everything. The directives can communicate using attributes, services, broadcast / emit or require their parents / siblings if they work closely together.
Is it a good practice to use events between controllers ?
No it's not, it will be deprecated by Angular JS 2.0. It also often leads to unmanagable tangle of events which are hard to understand and debug. Use services to share data between controllers. (Inject same service into multiple controllers, service then holds data, controllers bind to that data and are automatically synchronized) I wrote a blog post explaining this use case.
Is it good to use promise attached to scope for child controllers ?
No it's not. Use promises and resolve data in services. Don't use $scope at all but use controllerAs syntax instead. $scope was deprecated also in Angular JS 1.X because it's usage leads to many different problems with scope inheritance.
Will it improve my code if I start using services ?
YES! Use services for all logic and data manipulation. Use controllers only for UI interaction and delegate everything to services. Also use ui-router for managing state of your application.
I'm not going to answer your questions directly as I have some other comments as well. I think the approach you mentioned is not the best way to build angular applications.
All the common logic in Main Controller and all other options in different controllers as the child of main controller.
It's against all angular style guides to place common logic in controllers. Controllers should only be used for the logic related to the view (data binding, validation, ...). Because the code inside a controller is not reusable, the less code you have in a controller the better. The more logic you have in services, the more scalable your application becomes.
Fix: I suggest you create a service that retrieves data from the server, and inject this service in controllers as you need. Notice also this way offers better dependency management as you can keep track of which controllers need which services exactly.
Nested controllers should be avoided when possible, because angular keeps track of all the active scopes and re-evaluates them in every $apply() loop.
Fix: same as #1, use services instead of the main controller.
To make sure data is loaded I am using promise attached to scope. So all the child controller will know data loaded.
Using a promise for data retrieval is a good practice. But, again, keeping it in a service is much cleaner than main controller.
I have moved data updation part of all child controllers to main controller because all the updates happen in one object.
Child Controller emit/broadcast to communicate between child and main. So when update happens child will emit an event with data which will be captured by Main and it will do the update.
Fix: use a service with an update function instead of events. Events are harder to debug and track. And you need to unregister event handlers on destroying a controller. If you can use a function/promise instead of events, then it's usually a better idea.
Is it a good practice to use events between controllers ?
A problem with your current set-up is that you're implicitly relying on the hierarchy of your controllers (the fact that one is the child of the other) - because you emit the event, only scopes higher up on the hierarchy can catch it. Besides being an implicit connection (that a developer has to remember), this also limits he extendability of this feature.
On the other hand, if you injected a shared service into all the controllers that need it, the connection between the controllers would become explicit and documented, and their scopes' position in the hierarchy independent. This will make your architecture easier to maintain, with the added benefit of also being easier to test, for one.
You can still implement an observer pattern with a service.
is it good to use promise attached to scope for child controllers ?
The issue of polluting scopes pointed out in other answers is valid. This is one of the reasons why it's better to limit the number of objects you attach to your scope, and to use objects as bundles of variables on your scope instead of attaching all the variables to the scope directly.
(For an explanation of these reasons, see discussions about "always having a . in your bindings".)
(Of course, don't do this blindly just to reduce the number of variables, try to find semantic connections between variables that might be bundled together sensefully.)
Will it improve my code if I start using services ?
I think the above answers already outline the answer for this: yes. There are other benefits too, but this format is not best for too long answers, so I won't list anything else now.
All in all, these above pointers are not big issues with your code currently, but if you're looking for the best architecture, I think you can do better.
Answers:
No, it will be deprecated soon.
$scope is deprecated already.
Services is a great choice. Services allow us to share data and behaviour across other objects like controllers.

(another) request for clarification about the meaning of "singleton" in Angular

I'm learning angular, experimenting with different ways of using services/factories, and am trying to wrap my head around the unique sense in which they are "singletons".
I have an API service that exposes domain models and wraps functionality for retrieving them from my REST server. This service can be easily comprehended as a singleton in the classic sense: I want a single instance to be shared across my application, with a state that can be observed by many different controllers, enabling those controllers to "synchronize" with each other through the conduit of the service: The controllers stay in sync not by being aware of (and thus coupled with) each other directly, but by being aware of this common service. (side question: is this a correct characterization of the role of a service?)
This is a use-case where a singleton service is clearly and unambiguously appropriate. But:
One of the domain objects that gets returned by the API service is called thread, which is essentially a wrapper around a linked-list of points. In addition to the list of points, a thread has a currentPoint variable and a next() function, which pops the next value from the list and makes it the currentPoint.
My UI visualizes a thread simultaneously in two different ways - in two separate elements with their own controllers and directives. Each of these elements contains a button that, when clicked, calls nextPoint() and thereby changes the state of the thread. When this button is pushed in one element, the state of the thread needs to be updated in both elements - so, here again we have a situation where a service seems ideal.
But, at any given time, there can be an arbitrary number of threads being displayed, each of which should be independent and unaware of each other - which conflicts with (what I understand to be) the "classic" sense of "singleton".
Is there a word for this sort of thing in angular?
I've experimented/looked into this enough to know that it's certainly possible to create these "non-singleton singletons" using factorys, but surely there must be a better term for them than "non-singleton singletons" - I cringed both times I just typed it.
Second, what is the best way of implementing one? Can the strategy illustrated below (which I found in an angular github issue here) be regarded as a best practice?
myApp.factory('myServiceProvider',function(){
var serviceProvider=function(){};
serviceProvider.prototype.foo=function(){};
var service = {
getInstance:function(){ return new serviceProvider(); }
}
return service;
});
//Singleton Services
myApp.factory('myService',['myServiceProvider',function(myServiceProvider){
return myServiceProvider.getInstance();
}]);
//Where non-singletons are required
function myController(myServiceProvider){
var instance_a=myServiceProvider.getInstance();
var instance_b=myServiceProvider.getInstance();
};
//Where singleton service is required
function myOtherController(myService){
myService.foo();
};
An angular singleton is not exactly the classic. A singleton in angular is basically one instance of an object that holds a single state. That state can be data bindable via a services allowing for value sharing. This means that you can have a service property that is bound across all of its uses an app; one change will be reflected everywhere. The singleton persists through the life of the app. If the app is refreshed the singleton will loose value until it is set again by the app via a user interaction or a storage retrieval.
I like the pattern you are using. I also tend to use it. Here is an example of a web storage service I recently made similar to your service, https://github.com/breck421/WebStorage/blob/master/src/js/WebStorage.js.
I hope this helps and feel free to continue this dialog :)
Thanks,
Jordan

SPA design with AngularJS - sharing state across some, but not all, pages

How would you implement something like this in Angular:
I have a multi-page user interaction that shares state across pages/controllers. Page A launches a multi-page process across pages B, C, and D. I need to share state across pages B-C-D but as soon as the user goes back to page A (either at completion, or abandoning halfway through) the shared B-C-D state should go away.
I could put the shared state in a service and that would take care of sharing across pages. But then it's a global singleton for the whole application. Is there a way to ensure the service is disposed if the transaction is abandoned or completed?
In the server-side, Java EE world this was called "conversation scope" - I'm wondering what the equivalent might be in Knockout or Angular.
Or there a better way to approach the design? Should I use nested controllers?
This is a pretty broad question and is going to certainly elicit some opinion based responses. That said, one of the things you can rely on is that services (and factories) are singletons. What that means is if you need to share data between controllers, or across the life of a SPA you can create a service to hold and share that data. That service and its data will exist as long as the page isn't re-loaded.
The basic pattern for a shared data factory is like this is:
// define the shared data service
app.factory("SharedData", function () {
return {
// just one data object for the purposes of the example
sharedDataObject: {}
};
});
Once you have defined the service you can define a controller that uses the service something like:
app.controller("FirstController", function ($scope, SharedData) {
$scope.localData = SharedData.sharedDataObject;
});
Because we have defined the shared data as an object and not as a value - binding to "localData" will allow us to set values that can then be retrieved for as long as the page isn't changed. I put together an example that shows sharing data between two controllers here. This pattern works just as well if the controllers were on separate views.
Again - I'm not sure if this is the recommended pattern but it is one I have seen around and it works pretty well. Best of luck!
NOTE - This answer is referenced in your question - so it probably isn't exactly what you are looking for. That said, I am posting for others that may need a simple method of saving state on an SPA.
If you put the shared state into a service, just add a reset() function to it that gets called when they go to the "A" step or when they complete the process.
And I think you could do it with a nested controller too. You'd probably still need to add a reset() function for handling all the cases.

Categories