I have two services and a mediator. If I want the mediator to call AND be called by both services, I think that I need to make them dependencies of each other. This causes a circular dependency error.
Person Depends on Mediator to call Mediator methods
Mediator Depends on Person to call Person methods
Is the only solution to use events or promises? Am I implementing this pattern correctly?
this is a bit of a problem that extends beyond angular and into javascript imho.
the standard way to structure mediators to avoid circular dependencies is to use interfaces, but javascript doesn't have interfaces.
in your situation, if you have the mediator injected into the service and vice versa, yes there will be an error.
assuming your mediator is also a service, a work around is not to have dependencies injected into the mediator, but rather have the mediator initialized before it is ever used with the 2 services that you need it to mediate for.
the alternative is not to use a mediator object, but use the publisher/subscriber pattern which is built into angular with $broadcast and $on. imho, this gives even looser coupling than the mediator pattern, so it has my thumbs up
Only your services which utilize Mediator should depend on Mediator. A service which publishes events injects Mediator. A service which subscribes to events injects Mediator and registers callbacks contained within the service. The Mediator should not depend on either service, it should only contain map a publishing events to a list of callback references.
See the Mediator in Angular example I wrote here
Related
i have faced this question in an interview, i know how to share data between two controllers using service and also using root scope. Is there any way to do with in angular to pass data between two controllers without using service and root scope>
Any suggestions please.
AngularJs uses the Observer pattern which consists on sending and reading events.
There are many times when one part of the application changes, other parts needs to be updated. In AngularJS, if the $scope object updates, an event can be triggered to notify another component. The observer pattern incorporates just that - if an object is modified it broadcasts to dependent objects that a change has occurred.
In short:
$scope.$emit() OR $scope.$broadcast() depending on your position and what is your 'reader'
Then
$scope.$on()
The best practice states using a service, you could also use $rootScope by assigning object literal $rootScope.sharedVar. There's also a $broadcast method, which is an observer pattern, works like pub/sub.
The least recommended way would be leveraging your $parent scope and drilling down your element (depending where it's located in the DOM tree)
As a backend developer I am little bit struggling with Angular UI MVC concept.
I am trying to draw parallels to my backend MVC so I can understand mindset behind Angular better.
On my backend I have services talking to repositories(or DAOs (Data Access Objects) how we called them in past), controllers calling services to do the job(as they only transport data and not do heavy lifting) and talk to the client(ie browser) and my Model is a combo of(DTOs (Data Transfer Objects) and Entities as of ORM).
As I am inherently inspired by having backend only ever to return/accept JSON(big no to JSP,FreeMarker,Velocity and all others which make my testing life so hard). I would say that on my backend I only have Model-Controller. From the backend perspective my View is AngularJS as JSON data I return could be labelled as part of my Model but it is definitely not my View.
Now when I start to think about UI MVC as of AngularJS I don't understand who should use $http service to talk to backend. The endless examples scattered across the web do not help me. They are either too minimalist or don't show the usage of $http in the full context(simply called from controllers).
I could argue easily for both.
Case A: If AngularJS treats backend as Model then it is the responsibility of angular's services to call $http to talk to backend to retrieve/post data. Here angular controllers still act as basic transport between View and Model ocassionally calling services to get and process data from backend.
Case B
I could also say, hold on - "no", if angular's controllers role is solely to transport then they should get data from backend and deliver to required destination i.e. angular's service/view(if no further processing required).
So which one is "right"? Or at least widely accepted by UI/fullstack devs?
Controllers should only be connecting data and logic with the view and in the most minimal way possible. A bulky controller suggests that either the view needs to be divided up or logic needs to be abstracted into services. $http calls definitely belong in services. The controller doesn't care how the data comes, just that it comes. So:
// controller doesn't care how
getData().then(function(data) {
VS:
// controller is too concerned with "how"
$http.get('/the/path').then(function(data) {
It is typical to see $http calls in controllers in sample code, but not in professional production code.
I would strongly suggest Case A: having this in a service.
Think of Angular controllers as owning each specific piece of view they are assigned to, with services providing ready-made functionality for those controllers.
Also note that a single page can have many views, each of which could be bound to its own instance of a given controller. So it doesn't really make sense to have $http-based functions etc being instantiated a bunch of times. For a service, it will be instantiated once and then shared across any controller that injects it. This is also a great way to share data between controllers, and is one of the strongest reasons to use a service for any given task.
One other suggestion is that thinking of Angular as MVC can lead to issues. Angular is flexible enough to follow multiple design patterns, hence the MVW (Model View Whatever) moniker, but the majority of applications I have seen tend to follow the MVVM pattern. For this reason I would say that the controller should never have knowledge of $http in most cases.
I am trying to understand singleton pattern.
I write a lot of code in angular and recently I wanted to refactor some of my code and move it to a common place which can be shared by different controllers.So I moved all common utils to my services.
Now the documentation over here says that angular services are singletons but I want to understand the reason behind having singleton pattern here ? Why not have multiple instances of the service object instead of passing references to controllers ?
It all falls in the name "Service". Service, acts like a medium to communicate between controllers or even directives for that matter. Not only for communication, you can add a set of utility functions in your service, which can be used throughout the module/app. This does not need to have multiple instances to serve the purpose. Hence, singleton.
Angular services are the recommended way to exchange data and communicate between controllers. In order therefore to allow this data exchange, services are singleton objects which means that you are guaranteed to have the same service reference between all your controllers.
As an example, imagine that you have an Angular application that displays a list of messages received from another user in the center of the page, as well as the number of received messages or new message notifications in the header. The header and the page content will most probably be under different scopes and be handled by different controllers. In order for these two controllers to have the same view of messages received and be able to display them consistently they will need to use a singleton object holding this information. This object is an Angular service.
Getting The Scope of Another Module to Dispatch Events;
Acyclical Directed Communication Network
EDIT: THIS QUESTION IS UNDER REFORMATION.
Intention
What I'm looking to do is fairly straight-forward. I have an Application Core module which looks like this:
var app, application = app = angular.module('app', ['session', 'validation', 'summary', 'participants', 'ngRoute']);
...where each dependency is a module with its own $rootScope (SEE COMMENTS BELOW).
I intend on implementing a Mediator -- not an EventHub. EventHubs are simply a skinny-waist to which subsystems can publish and subscribe to broadcast channels on a specific medium. What I want is a true Mediator -- which, according to GoF, actually manages security of how and where modules communicate, in a unicast model.
That said, I cannot solely rely on using $rootScope.$broadcast/$emit as this will allow any & every module to listen to events from other modules -- without any control or intervention (mediation) from a centralized mechanism.
Problem
The problem arises when there is one module firing an event, say, 'excuseFileLog' and other listening for 'excuseFileLog' -- while the mediator is listening to this event from one module and dispatching it for another. Mediator is listening for one module to say "please excuse the 'FileLog'" and telling another that "an excuseFile has been logged". This is very semantic, as excuse, File, and Log are each, both a verb and a noun. So when Mediator dispatches this same event that it, itself, is listening for -- we enter an Infinite Loop:
// mediator is the sole medium for channels
mediator.on('excuseFileLog', function(){
mediator.fire('excuseFileLog');
});
Solvent
Put simply, I need to be able to access each module's $rootScope and fire events on that module alone -- hopfully, without the need of creating a service that will have to be injected into every module; which will encumber the developer with having to remember to implement the service and creating slightly tighter coupling. If a service is involved, then I may as well implement my own mediator/eventing-system, as apposed to leveraging Angular's eventing system. As the rest of the team is somewhat novice, I would prefer to keep 'chores' to a minimum.
Any help is very appreciated :)
I have a WPF application in PRISM architecture.
From what I read on the net, I saw that it is best if the View-Models call WCF service operation i n an ASYNC manner, and also - it is best to create a new connection for each operation. (I was told it is not good to keep connections alive for too long).
My question is - how should I inject the WCF clients to my View-Model ?
If I simply create an interface for the 'auto-generated' client - and inject the interface - this will simply create an instance for the client in my View-Model constructor, but that will not help me if I want to create a new client for each operation I perform in the window.
For that - I need something like a 'client factory' to be injected.
Can anyone offer his opinion on this ?
First off, IMVHO the WCF call is best to go in the Model, not the ViewModel.
You can create a factory helper class, you pass it an interface and it passes back a concrete instance that implements that interface. The factory helper can still use PRISM to resolve the interface to a concrete type, the types will resolve whatever you have registered them to, and you will get a new instance each time provided you haven't registered them with a lifetime manager.
Using PRISM inside the factory helper helps keep the whole thing highly unit testable - you can mock out the WCF related proxy classes at test time, and the target Model will never know the difference. If you really want to follow the dependency injection pattern then you could inject the factory helper on the constructor.