Best practice for node - mongo - angular - javascript

I have an app I am designing using node/mongo/angular, what I am not getting is how is the best way to get my data from mongo into my pages? I can use node, and thru my routes send back data from mongo with my template(hogan in this case), and bind using mustachejs. That works fine for most things. I have one screen that has a decent amount of drop down lists, to bind them for an edit scenario now seems a challenge. I would like to get them bound to an angular model and go about it that way. Is it better to get the data thru the route in node, then use something like ng-init and get it into angular? Or would I be better off not getting the data thru the route in node, and then using angular to perform a "get" request and bind that way?

From the documentation of ng-init, more precisely from the red warning alert at the top of the page...:
The only appropriate use of ngInit is for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.
So no, do not use ng-init. While that can be a good strategy for lazy migrations from regular applications to single page applications, it's a bad idea from an architectural point of view.
Most importantly, you lose two things:
An API. The benefit of SPAs is that you have an API and that you're constantly developing and maintaining it, even before it has external users
A clean separation of concerns. Views are strictly limited to presentation, can be cached by the client and all data is transferred through JSON API endpoints.

I would say that the best way to get data from Mongo into your page, is as mnemosyn said, using an API.
Basicly, you can have your API route, f.ex '/api/data' configured and then it can be used by a angular service, (which can use ngResource to make things easier). Any controller that wishes to access this data can use the angular service to get it, do some stuff with it, and then update it using the same angular service.

Related

Initialize the server data from ng-init directive via calling angular controller function?

We have developed one Enterprise application, The complete client side framework is built on AngularJS and the server side framework is on ASP.NET Web API. In the application we have 350+ html pages and 250+ Web APIs. There are lots of areas where we initialize the server data from ng-init directive via calling controller function. Because in our application all data is coming from the ASP.NET Web APIs. But I was surpised upon the documentation for ng-init, which says, in a nice bold outline :
The only appropriate use of ngInit for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.
I would like to get feedback from Industry Experts/ Angularjs Core Team Members on my concerns.
Let me brief first what we are doing in the application, for showing a industries list we load the industry HTML page and show the server data. The HTML template code is shown below:
<div ng-init="initIndustries()">....</div>
The "initIndustries" function will be called from initialized industryCtrl. industryCtrl.js code is shown below :
app.controller("industryCtrl",["$scope",function($scope){
//Sets the server data in the $scope property.
$scope.initIndustries = function(){
//perform ajax request and set the data into the $scope property.
}
$scope.initAddIndustry = function(){
// perform ajax request for getting a dropdown data on Add Industry Page.
}
}])
I have few concerns based on Angularjs Doc and Anglarjs-styleguide guideline on Keep Controller Focused which is mentioned below :
Are we doing something wrong to initialize the data via function because all data is coming from the Server APIs?
Current initialization approach is against the industry practices in AngularJS based application. if yes, then which approach we need to follow in the application?
Do we need to create sperate controller for every view just for the shake of client side test coverage, as per the angularjs-styleguide?
The reason to implement the above approach(initialize the data from ng-init directive via controller function), Due to large application my initial thought was to follow MVC philosophy of decoupling the code and separation of concerns.
Angular is known to be Model-View-Whatever. So, it totally depends on you whether you follow a structure in the angular application or not.
Not following a structure has some pros and cons.
Pros
1. A data that is available in one controller can be shared across many views so you won't have to use $rootScope or HTML5 localStorage/sessionStorage to pass data from one controller to another.
Cons
1. As data in controllers is available in multiple views so it is very difficult to maintain the data because the data is obviously bound to views and there will be many implicit angular watches on the same data. That will give bad performance.
Now answering your point 1 and 2 of using ng-init to intialize data in controller. I don't think that will be a good approach because you have made the initialization dependent on the view.
Lets take a scenario in which your view is not found on request and then the initialization won't occur. And as initialization won't occur, there will be garbage values / bugs in controller. So its better to separate the controller initialization from view.
Answer to point 3 is that when you are using a separate controller for every view, you are actually avoiding monolithic code approach and that is always a good point because that leads to modular approach. Separation of concerns in Angular JS is not just done using separate controller for every view but services and directives are also for this purpose in the long run.
Hope that helps you in some way.

Angular JS and Symfony2

I am currently working on a project using Symfony2 and seeking some advice on that.
I am thinking of a hybrid application in two(2) different ways a) Login Page shall use traditional form with CRF Token and let symfonty2 handle it. b) All Inner pages ( which potentially are modules ) I want them to be non AJAX, but the other activities inside that shall behave like a Single Page.
For example I have an employee module. When user clicks on that it is entirely loaded from Server ( all the templates and forms etc ) now each activity under employee module like add/update delete/view etc shall be loaded through AJAX and response to be returned in JSON i.e AngularJS.
I am currently thinking of using FOSUserBundle to return html on initial request and then based on request type Accept: application/json it will return the JSON ( remember the add/updat delete/view part? ).
My question is it a better idea to use Angular Partials (html) files or Symfony2 Twig? or would it be better to use Angular JS, but let those partials be rendered by Symfony2 twig? ( I am thinking of Forms here, would want to validate that both from client and server side )
Has any one been through similar problem, if yes then what approach was used to develop HYBRID application using AngularJS and Symfony2 or any other framework? any relevant ideas are appreciated.
I was in the same situation you are. AngularJS+Symfony2 project, REST API, login using FOSUserBundle, etc.
... And every way has pros and cons, so there is no right way, i'm just gonna say exactly what i did.
I choose AngularJS native templates, no CSRF validation, a base template built using Twig, server-side validation, use of the FOSJSRoutingBundle, and some helpers (BuiltResponse and BaseController).
Why native templates?
With the use of verbatim, we solve the variable problems, but we gonna have a more complex logic in our templates.
We also will have a less scalable application. All our forms templates are doing a request in the Symfony application, and one of the best pros of the AngularJS is load our controllers, templates, etc from a storage service, like S3, or CDN, like Cloudfront. As there is no server-side processing, our templates would load so much faster. Even with caching, Twig is slower, obviously.
And both, Twig and AngularJS templates, are really complex to manage, in my own experience. I started making them together, but was painful to manage.
What i did?
I created static templates in front-end, with the same field names, it's not really good. We need to update the templates every time we update the forms, manually. But was the best way i found. As the field names are equal, we won't have problems to ajust the model names in the Angular controllers.
And if you are creating the software as a service, you will need to do it anyway. Will you not load the form templates from the application in a mobile app, right?
Why no CSRF validation?
We don't use CSRF validation in a REST API, obviously. But, if you wanna do it, you need to make a request every time you load a form, to get the CSRF token. It's really, really bad. So, we create a CRUD, and also we need to create a "csrf-CRUD", 4 routes more. That doesn't make any sense.
What i did?
I disabled the CSRF in the forms.
Base template?!
Yep. A base template is just to load any route in our application. Here is what i'm doing:
This will help us to avoid errors when users are going directly to some Application URL if you are using html5 angularjs urls. Simple like that.
Server-side validation, why?
If we do a validation in the Angular, we need to do the same in the server-side, so we have 2 validation codes to maintain. That is painful. Every change we do in the form, we need to change the validation in the front, validation in the back and also the Angular static form. Really, really painful.
What i did?
I basically did a server-side validation using the Symfony constraints. For every request, the application validates the form and check if any error was found, if yes, it gets the first one and send it as a response.
In the AngularJS, the application checks if there is any error inside of the errors key. So, we have a proccess used in all application to do any form request. It's like that:
And the routes?
There is another problem: the routes. Put the url directly is not a reliable way. If we change anything in the url, that route is gone and the users won't like that.
To fix that, we can use the FOSJsRoutingBundle. With that library, we can put the route name directly in the Angular controller, and it will fill with the exact url of the route. It's completely integrated with the Symfony, so parameters will work very well.
Instead using the url directly, we can do it:
Routing.generate('panel_products_show', {id: $routeParams.product_id});
And voilá! We get the route url.
That will solve the biggest part of the problems you have. But there are more.
Problem 1 - Form inputs
The forms from Symfony generally have a prefix, like "publish_product", so every field has a name like [publish_product]name. Ah, how that was a problem for me.
In the Angular, publish_product is not considered a array. You need to put the single quote to do this, like ['publish_product']name. And it's really bad, we need to change every key to use this format. In AngularJS, i was doing like that:
{{ formData('[publish_product]name') }}
Absolutely stupid.
The best solution was simply remove the form prefix in the Symfony, using the createNamedBuilder method instead just createBuilder. I let the first parameter null, and yeah, we don't need to use the prefix anymore. Now, we use:
{{ formData.name }}
So much better.
Problem 2 - Routes hard do maintain
Every request can return anything, i need to repeat much code. That is really hard to maintain, so i just create some application rules, built responses, a BaseController, etc.
createNamedBuilder
createNamedBuilder is a big method. We need to do this, for every form we have:
It's simple to solve. I just created a BaseController and i'm extending every controller from it. I created a simple method that does it.
For every route, we do not need to repeat 3 lines, much better.
Responses
When my application started growing, i had a serious problem: all my responses are different. That was really hard to maintain. For every request i was doing, sometimes i was using "response", sometimes "data", the error messages were lost in the response, etc.
So, i decided to create a buildResponse, that i just need to set some parameters and i get the same result for every route, even GET routes.
response key shows me the status and the message. It can be error or success, and the message os a optional field, that can come blank. For example, a success status with the message "You created the product".
data key shows me any information i need. For example, the user added the product, and now he needs the link to see it. In the data, i put the url of the post, and i easily can get it from the AngularJS controller.
notifications is a specific key for my business logic. Every action can return a notification to the user.
It doesn't matter what keys you have. The most important thing is have a standardized response, because when your application grows, it will be really helpful.
That is a route from my controller:
Completely standardized. The Scrutinizer code quality tool says all my routes are duplicated. :D
Have a BaseController and a builtResponse will help you so much. When i started refactoring my code, each route lost about 4-10 lines.
Details: getFormError return the first error of the form. Here is my method:
public function getFormError(FormInterface $form)
{
if ($form->getErrors()->current()) {
return $form->getErrors()->current()->getMessage();
}
return 'errors.unknown';
}
... And the parameters from the buildResponse are:
1. Status. I get it from a constant in the BaseController. It can be changed, so i believe is important do not use a string value in each route.
2. The translation message. (I use a preg_match to check if it has a translation format, because getFormError already translates the error).
3. The data (array) parameter.
4. The notifications (array) parameter.
Other problem i'm gonna have
The project just have one supported language until now. When i start to work in a multilingual version, i'm gonna have another big problem: maintain 2 versions of the translations: the back-end messages and validations and the text from the front-end. That probably will be a big problem. When i get the best approach, i'll update this answer.
I took some months to get the this approach. So many code refactorings and probaly much more in the future. So i hope it help someone to do not need to do the same.
1. If i get a better way to do this, i'll update this answer.
2. I'm not good at writing english, so this answer probably will have many grammatical errors. Sorry, i'm fixing what i'm seeing.

Where to format collections / objects

From front end architectural point of view, what is the most common way to store scripts that perform transformations on collections of objects/models? In what folder would you store it, and what would you name the file / function?
Currently I have models, views, controllers, repositories, presenters, components and services. Where would you expect it?
As a component (what would you name it?)? As a service? Currently I use services to make the connection between the presenter and the repository to handle data interactions with the server.
Should I call it a formatter? A transformer? If there is a common way to do, I'd like to know about it.
[...] models, views, controllers, repositories, presenters, components and services. Where would you expect it?
services, mos def. This is a interception service for parsing data.
Should I call it a formatter? A transformer?
Well, trasformer (or data transformer) is actually quite good IMO. data interceptor also comes to mind, and data parser, obviously.
If there is a common way to do, I'd like to know about it.
Yes, there is! Override the model's / collection's parse() function to transform the data fetched from the server into your preferred data structure.
Note that you should pass {parse: true} in the options to make it work.
This, of course, does not contradict using the services you wrote from within that function. You can encapsulate the parsing logic in those scripts, and reuse it anywhere you'd like.
Bare in mind that there will probably be very little code reuse when using parse(), as each transformation will relate to a single model or collection.

Angular: How to go about refreshing service data

I am fairly new to Angular and trying to build an Angular application.
I have a lot of data that needs to be used by multiple controllers throughout the app. As I understand it, that is the perfect situation to use a service.
I am planning on storing this kind of data in services. For example I plan on having a users service which all controllers that need user data will inject.
I would like the users service to hold the master list of users and any controller that needs users to just use the one instance of service list.
I am having trouble envisioning the pattern though. I mean:
1) What is the standard way of having the service refresh its data from the server? I realize that I could just go and request the entire list of users every 10 seconds from the server but that seems kind of heavy weight...
2) Ideally I would like to be passing around only a single instance of each user. This way if it gets updated in the service, it is sure to be updated in all of the controllers. I guess the other option is to have the service broadcast an event every time it updates a user? or to use watchers?
3) What is the pattern by which the controllers interact with the service and filters? Do the controllers just request data from the service and filter it in the controller? The other option is to have the service do the filtering. If so how do I communicate the kind of filtering I need done to the service?
I think that by using some kind of solid pattern I can take care of alot of these issues (and more that I am sure will arise). Just looking for advice on some common patterns people employ when using singleton services.
Thanks in advance.
Answer to point 1. A service is just a singleton. How you store and refresh data into it has nothing to do with its nature. Not sure why you want all user data inside a service (unless you are building a user management app), but you could use several techniques like polling (eg. using $timeout ask for new users and append them to the existing ones) or push (eg. socket.io/signalR which will push you the payload of new users when available). This can be done both inside the service itself or by a controller that will add/remove data to the service (eg. a refresh users button in the UI)
Answer to point 2. You can bind/use the reference of the data inside the service directly into your controllers using a getter so that changes to the data are shown instantly (given that are two way binded, if not use events).
Answer to point 3. You can apply filters inside the controllers or in the view it self (not recommended). You can also have a function in the service where you pass the filter or filter params and get the filtered copy of the users collection back (since you will be using the users collection directly in many controllers at once you shouldn't modify that, unless that's desired). If you are reusing the same filters again and again across the controllers you can have a function for each filter that returns the filtered collection with a "hardcoded" filter. You can even have helper function in the service to help you assemble complex filters or have multiple copies of the collection already filtered cached(if you find you are using the same filter again and again)

Angular.js: templates and handling data between views

I'm trying to grasp the main principles related to the next issues:
Templates
Data Handling
$resource vs $http
As i see it i'd like to implement few views in my app which share few html templates and also share some data. for simplifying my issue i'll describe a scenario which is almost equivalent.
as u can see there are 2 views (though there will be more!) who use 3 html markups while one of them is shared in both views (GeneralInfo). Also, both views share data which will be normally created while using one of the view's controller.
What principle of angular should be used to make sure that while changing the route i could keep my data shared between the views.
Should i use app.value('myVal', ..) which is Global variable?
Should i pass it like a service to all of my controllers?
More technically, how should i implement same html in both views? could u example that?
How should a view with it's markup contain 2 templates and how and when it is rendered?
what's the difference between $resource and $http and when each shouold be used?
1) should use a Service to share data between controllers. technically, you could attach values on $rootScope and it would be visible across controllers, but that is considered bad form and can cause problems later (like using global variables -- can definitely have unintended side effects as the project grows if someone accidentally attaches a conflicting value).
2) not sure exactly what you're asking here. you can load a partial based on the given route/state (using ngRoute or ui-router). two different routes could use the same generalInfo.html partial, but with different data being pulled in their respective controllers. is that what you're asking?
3) $resource is an abstraction of $http -- if you're pulling data from a REST server, $resource may be a better fit, as it abstracts a little of the wiring necessary. however, if the server varies from traditional REST principles too much, or if it's not REST at all, you may just want to roll your own data access directly with $http. Of course, if it's REST and more complex, also consider restangular -- which is a more feature rich abstraction.

Categories