Hi I'm building an angularjs app that has a timer throughout the application. Every minute I will be polling the server to see if a user has gotten a new message in their inbox.
I was wondering what is the best way to design this? I see two options so far:
1.) Rootscope function
2.) A Service
The problem with the service approach is that I have to inject this service to every controller I have. Does anybody else have any suggestions on how to design this app?
Thanks
Use a service - it's a cross-cutting concern that some, but probably not all of your controllers need to know about. Injecting it where it is needed does involve some extra keystrokes at first, but it's a benefit, not a problem - it keeps your code modular and easier to test.
If you use a service, you can inject a stubbed instance into your controller tests so you can test the controllers in isolation. You can use Jasmine spies (for example) to return mock values from your service, so you can easily test how your controllers behave with a range of inputs.
Related
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.
Why do we need services or factories, we can also do the same thing by making a normal javascript function, or writing the logic in the controller itself.
For example, when i get json data from the server using '$http.get', i can do it by writing a separate service for it but why is it even required when we can directly write its code in the controller?
This is a good question to ask for clarification before digging into Angular as understanding the parts will enable you to write good Angular code and not just do something because you can.
http://i.stack.imgur.com/BKl1Y.jpg
This is a good visual for Angular as an MVC.
The simple answer to your question is that services should be passing information through your controllers to your various pages and routes. All information logic shared across these views belongs in the service. Controllers pass along that information from the view to the service and from it. Information and logic local that view that doesn't need a broader scope can stay in the controller. This is the clean separation that makes Angular a strong framework.
I was wondering what is the preferred way to make different part of an app interact with each other.
For instance let's say we have a directive A that display a product in the shopping basket of a user. This directive has access to a persistence service that allows CRUD operations on the item.
Let's also say we have a directive B that displays a general message.
Now the user decides to delete a product from his basket. Is it acceptable to make it publish an event this way?:
$scope.$emit("item-deleted");
and then have B listening on that type of event:
$scope.$on("data-received", function(event, next, current) {
// show up and tell "item deleted succesfully"
});
Is it a good way to achieve the result? It definitely is in other frameworks and in UI development in general. I was just wondring if it is a viable way in angular.
Thanks
You should use services instead of events propagation. With the dependency injection, it is really easy to use. It is the best way to make two controllers to talk to each other.
More on services : https://docs.angularjs.org/guide/services
create a service for directive B which will provide data for general messages.
inject that service into the underlying service of directive A. then call that service with proper message.
Directive A should auto display this data, because of 2 way data binding of angularjs.
tl;dr
I'm really struggling to find the appropriate pattern here. How should I best configure a generalized provider to a specific use-case? I can't use $http as a dependency in .configure(); can I?
longer, boring explanation:
I am trying to create a generalized provider which I may reuse in Angular. I have it working, however it requires configuration.
The intention is to provide a fallback REST service to use in saving data to the server, but with provision to save offline in local-storage. Therefore, I need to provide appropriate $http calls for each instance of this provider.
Is it possible to provide appropriate $http calls with .configure() or else should I try and figure out how to inject $http into the provider from the start and then configure it afterward??
It's frustrating... and may change in AngularJS 2.0... But for now, yes, it is not possible to do this. There is a very high wall between the .configure() and .run() states, so you can't access $http from a .configure() function. The reason is that it hasn't actually been created. At this stage, all that exists is the provider. Once all of the dependencies are configured, then the http provider will be used to make the real $http service.
I'm not sure exactly what you're trying to do, but there are two excellent AngularJS developers that are good to follow who have some advanced patterns in projects they've shared: Pascal Precht and Brian Ford. Here are two projects that make heavy use of provider/service concepts as well as $http-driven services:
https://github.com/angular-translate/angular-translate
https://github.com/btford/angular-modal
Angular Modal, especially, does $http work to load its templates. There might be use cases in there that are similar to what you're trying to do.
I have an application which has some specific (non-trivial) initialization requirements, and it's not really clear what the best practice solution to this is. Sorry for the wall of text. The question itself is not that complex, but I need to make sure my reasoning is clear.
First, the application itself:
It has user authentication, though it is only forced at two points in time:
The first time the application is loaded (the very first time). I'll just call this requirement (1) through the rest of the question.
On a need-to basis when interacting with server-side. This part I have already solved with something similar to http://ngmodules.org/modules/http-auth-interceptor, though a custom solution (which is required because the application needs to use some services that I don't want to be Angular dependent). I'll call this requirement (2) through the rest of the question.
There are two controllers relevant to this question:
A navigation bar controller (fixed, not bound to the view).
The controller applied to the view used (ng-view).
It is started manually using angular.bootstrap.
This question is about the user authentication handling. Requirement (2), where a user has to authenticate on a need-to basis, is already solved. It is currently handled like the following:
Some server-side request is performed by one of my Angular service modules. The request can potentially result in a 401 response if the applied authentication token has expired (or doesn't exist all-together).
The application service module which made the request discovers the 401 response and applies a $rootScope.$broadcast('app:auth').
The authentication broadcast is picked up by some code using $scope.$on('app:auth'), shows a modal authentication dialog, and then makes sure the original service request promise is resolved / rejected (rejected if the user presses cancel in dialog).
The only differences between requirement (1) and (2) is that (1) should be a forced authentication dialog (the user cannot simply reject it with 'cancel' or 'esc'-button) and that (1) should happen as early in application initialization as possible.
Now, my issue is with requirement (1), really, and Angular best practices. There are a couple of ways to do this that I can see:
Perform this one-time authentication outside of Angular completely. The downside here is obviously that I have to write essentially duplicate logic for both the modal dialog box and the initialization. Some of this can be shared, but not all.
Perform this one-time authentication in some special (fixed) controller of the application (like the navigation bar controller).
Perform this one-time authentication in angular.module.run.
The aim here is obviously to "force" an authentication on the user before he (or the application) can trigger something else in the application.
I would love to use number (3), since I would then be able to re-use all code already in use by requirement (1). However, you then instead run into the question of where to place the event-listening code. No controllers / parts of the application are yet started at this point (only the injections are complete).
If I place the logic for authentication events in an application controller, that controller won't even have started at that point, and thus won't have been able to register with the event. If I place the $rootScope.$broadcast inside a $timeout with 0 delay, my navigation bar controller have started, but not my view-bound controller. If I place the $rootScope.$broadcast inside a $timeout with 100 ms delay, both my controllers have started (on MY computer).
The issue obviously being that the amount of delay I need to use is dependent on the computer and exactly what scope the event handler code is placed in. It's also probably dependent on exactly in which order Angular initialize the controllers found through-out the DOM.
An alternative version of (3) might also be to do the $rootScope.$broadcast in angular.module.run, and have the event-listener attached to the $rootScope itself. I'm leaning towards this being the most straith-forward way to do it.
See the following plunker (which tries to higlight the timing issue only): http://plnkr.co/edit/S9q6IwnT4AhwTG7UauZk
All of this boils down to the following best-practice question, really:
Where should application-wide code and non-trivial application initialization code really be placed? Should I consider the $rootScope as the actual "application"?
Thanks!
The short answer :
Application wide code should be in a service.
Application initialization code should be in the run block.
Longer answer :
Application wide code like your Authentication should be defined in a service. This service should expose API's which the rest of your application can interact with in order to achieve that task. Ofcourse the job of the service is to hide the implementation details. The service itself should take care of where it fetches the authentication information from ( initially ) - perhaps from cookies, perhaps from your local storage or session storage.. Or perhaps it even does a http call. But all this gets encapsulated into that Authentication Service.
Because now you have written a separate service and you can inject stuff into your run block you are good to go. You dont really need the $rootScope. The $rootScope is another injected service. But because it participates in the dirty checking mechanism and seemingly this service need not.. you dont need to over burden $rootScope with this additional task. Its not its job and perhaps it can be delegated to some other service whose only task is authentication. Because your service is also a singleton it is amazing at maintaining states as well. You could perhaps set a flag , something like isAuthenticated which can be checked later if need be.
Oh, between your modal should also be a service.. See the $dialog service in Angular UI if you havent already. Which means that authentication can directly work with the $dialog service.
You should put application-wide non-trivial initialization code in providers. Providers offer the most flexibility with regards to initialization, because they can be used to configure the service before the instance of the service is actually created by the $injector.
app.provider('service', function() {
// add method to configure your service
this.configureService = function() { ... };
this.$get = function (/*injectibles*/) {
// return the service instance
return {...};
};
});
The config block is your opportunity to initialize your providers. Inject your provider into your config function (notice the required 'Provider' suffix) and perform any initialization code that you need to setup your provider. Remember, that the provider is not the service - it is the thing that the $injector will use to create your service.
app.config(function(serviceProvider) {
serviceProvider.configureService();
serviceProvider.setTimeout(1000);
serviceProvider.setVersion('1.0);
serviceProvider.setExternalWebService('api/test');
... more configuration ...
};
There are several reasons why providers and config blocks are suitable for initialization:
config blocks are called only once and very early in the application life cycle
providers are configurable - meaning you can initialize the provider before actually creating the service.
The main purpose of the config block is initialization. It supports injection of providers as an opportunity to perform the initialization.
Providers are singletons (like factories and services) - meaning that one service instance is created by the $injector and then shared between all controllers, directives, etc - basically any where that the service is injected.
Now for requirements (1) and (2) - I think you're on the right track. I suggest creating an authLogin directive that shows or hides a modal login dialog based on an "IsAuthenticated" property that is being watched on the scope. This would take care of the requirement to show the login modal dialog when the application starts up. Once the user authenticates successfully, set the IsAuthenticated property to true (which would then hide the dialog).
The second requirement is handled through an HTTP interceptor. When a request is made and the user is not authenticated, the service would broadcast the event starting from the $rootScope downwards towards the child scopes. You can have the same authLogin directive listen for the event and handle it by setting the IsAuthenticated property to false. Since IsAuthenticated is a watched property, it would trigger the modal login dialog so the user can log in again.
There are many ways you could implement requirements (1) and (2). I offered a slight variation on your approach, but in general it is the same approach.