Aggregated Data vs RESTful Resources for AngularJs SPA - angularjs

I am working on a single page app using AngularJs Framework.
The website is kind of social networking and thus consists of various kinds of data to be fetched from server.
Will it be good to be RESTful and make each entity a 'resource' or implement other way to get 'aggregated JSON' response, since RESTful results in too many calls ?
If non-RESTful approach is used, ( say by using $http service ), then how can I still maintain the modular architecture of app.
Consider example for clarification:
let the server return:
{
user: {
name: ....
....,
projects: [{
....
....
}],
...
}
}
How can I create modules such as User and Projects, each with its own functions and logically separate and independent.
Its almost similar to making single $http request and distributing response to many services.
Any help is appreciated.

Disclaimer - I am by no means a REST expert or purist
This is a very good question and something I struggled with as well. I just couldn't justify having X number of REST calls to display a single form/page, where X could sometimes be fairly large. The solution I ended up with which seems to work reasonably well in my case was a hybrid approach. I use aggregates (View Models) to render the forms/pages, these View Models I get from the server with a single API call. For create/update/delete operations I extract the actual resource from the View Model on the client and post that using a more RESTful approach.
This gives me best of both worlds, low number of API calls to display page, RESTful approach on post which reduces network overhead.
In addition to the above I use an approach I saw on breeze.js documentation which seems to work really great as well, on application startup I load all commonly used static lookup data (typically data used for dropdowns/select lists) in a single LookupsAggregate and cache that on the clients. This model is then available from the start and no need to refetch them everytime you need to display a dropdown/select lists.

Related

Should I filter data in backend or frontend?

I have a web service built with Spring, my view is built with React and I use Redux for state management.
Let's say my API has an endpoint /api/products and I've implemenented search functionality, which pulls all the products from the enpoint, stores them in Redux store and displays them. Now I want to implement sorting functionality and I have two ideas for achieving it:
Modify my api endpoint /api/products to take parameters. For example /api/products?sortBy=price (less logic in UI, more network requests)
Use the products that I have stored in the store. (less network requests, more logic in UI)
Which one of these, if any, would be considered as the best practice?
It would depend on
What is the acceptable latency? How often do you need to call this list? Almost every second, like in an autocomplete field? Say, a few times a minute, for a report which is sorted by different parameters by the user? Or something like a rarely used settings page?
How much data do you have? Is it a few million? or a few dozen? If it is too many, better to filter in the backend and send only the required rows.
How big is each row? If each row is big with many fields, your payload will increase.
Are you having to make a tradeoff between initial load time (to load all the data from the backend once) vs responsiveness (when the user is interacting with the data)?
I hope this will give you the general idea on how to decide. Maybe able to discuss more if you have details of your specific situation.
You have to use backend. If you have like 3000 records, you need to use pagination. You shouldn't sort all pages on frontend, because it would be too much data. You need to use backend to sort and send only data you want to display on specific page.
Please dont use backend functionality in your Frontend.
Spring Boot is an great framework and offers you Sort and Pageing functionalities.
Example:
public interface UserRepository extends CrudRepository<User, Long> {
Page<User> findAll(Pageable pageable);
List<User> findByLastname(String lastname, Sort sort);
}
Please look into the Documentation -> Spring Data Jpa

Designing a blog using Angular JS

I want to design a blog which will contain several articles. In the home page several tiles will provide links to the articles and when a user clicks on a particular tile with an article's title on it, he will be redirected to a new page having that complete article.
I understand that making a single page application will be of little help in this case.
Will it make sense if I design the whole website using Angular JS? If yes, how should I proceed if I want to design it using Angular JS? Should I avoid using routing since I've learnt that it is primarily used for SPAs, and shall I use $location or something for this instead? Or shall drop the idea of designing using Angular JS at all? Has anyone of you ever designed a multi-page application using Angular JS?
Your guidance will be helpful.
Before identifying the language to use for designing an app, it is important to understand what your app would be doing. In your case, a blog.
and if you analyze the app's functionality, the below three items (there are/could be more but for this use case, these three are sufficient) gain prominence:
Flow
Data
UX
The 1. Flow says that you may not have a SPA but a MPA, which means considering the resources that go into making of the pages, the user experience, it being a blog, a user may not have all that commitment (or patience) to remain with the blog if each click results in a request sent to the server and a heavy duty page served for the user to read through. This means that routes (Express or Angular) are ideal to navigate the user through the blog.
Data
A blog typically contains text and users may perform text search, which means that you need to figure out the right data store for your data ie., text.
This leads you to select the most optimally suited database that is also economical - SQL Server provides for Full text search at a cost of some hefty dollars; MySql does, too, and obviously with no or lesser cost; MongoDb, a document db, gives you the same and with no additional cost (unless you opt for the cloud model). So, SQL Server is not ideal since the app is not (most likely not, being a blog) meant to generate any profits; MySQL is ideal if you use a PHP server and PHP dev; MongoDb is ideal because it enables wrapping the model with the request object thereby, eliminating extensive coding to read the DB and write to the view.
Eg.
(in the router page of the landing Blog page)
var router = express.Router();
var posts = mongoose.model('BlogPosts');
router.get('/get, function(req, res) {
res.json(req.posts); // As simple as this
});
(in the view)
<div ng-repeat="post in infiniteitems">...</div>
(in the controller)
$.ajax({
url: '<url to your route>',
type: 'GET',
dataType: 'json',
success: function(data) {
$scope.infiniteitems=data; // Binds to the controller item in the view
$scope.$apply();
},
error: function() { },
beforeSend: setHeader
});
So, you have the navigation, the view, the data all taken care of with just a few lines of code. More importantly, no innodb or database engine
The code is meant only for explanatory purpose.
Because MongoDB returns a document as JSON and binding a view to a JSON is pretty simple than binding an object or XML values!
Obviously, this means a MVC framework and so AngularJs is the right choice.
UX - Angular Material, when used in conjunction with AngularJS, provides some scintillating designs, colors and animations and the simplicity adds to performance, enhances the UX and renders a freshness to the View (for the user) that is not easily creatable with other technologies.
So, go for Angular.
And also, because MongoDB works pretty well with NodeJS, the whole thing works together which is why they call it the MEAN stack - MongoDB, Express, AngularJS, NodeJS!

Who's responsibility to call $http? Service or Controller?

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.

The best way to pre-populate remote data in AngularJS app

In my AngularJS app, I need to retrieve multiple collections of static data from remote REST endpoints. Those data collections will be used throughout the entire application life cycle as static lookup lists. I would like for all those lists to be populated upon the initial application startup, and to be retained and made available to multiple controllers. I would prefer not to load any additional data dynamically, as one of the assumptions for this particular app, is that, once loaded, any further network connections may not be available for a while.
It is OK to take an initial hit, as the users will be preoccupied by reading a static content of the first page anyway.
I was thinking of making this mass loading a part of the initial application run block, and stick all this static data into various collections attached to the $rootScope (which would make that available everywhere else)
What is the best way to handle this requirement?
Interestingly enough, I just wrote a blog post about extending the script directive to handle this very scenario.
The concept is simple. You embed JSON data in your page when it loads from the server like so:
<script type="text/context-info">
{
"name":"foo-view",
"id":34,
"tags":[
"angular",
"javascript",
"directives"
]
}
</script>
Then you extend the script directive so it parses the data out for you and makes it available to other parts of your application via a service.
if(attr.type === 'text/context-info'){
var contextInfo = JSON.parse(element[0].text);
//Custom service that can be injected into
// the decorator
contextInfoService.addContextInfo(contextInfo);
}
You can see a live demo of it here: http://embed.plnkr.co/mSFgaO/preview
The way I approach this is to use a service (or a collection of services I nest), and set caching to true in the $http get functions. This way the service can be passed into any controller you desire, having cached results available to you without the need for additional http requests.
I can try to put this into an example if this is unclear to you, let me know.
edit: you can either wait for the first call to this service to do this caching, or do this on app load, either way is possible.

In my Angular.js app - Should I bind to the model that the Web API provides

I'm building an application with Angular and ASP.Net MVC.
All the data that I use in the application is provided by a Web API (I'm making Ajax calls to my ASP.Net controllers, which in turn call the Web API and return the API's response to the html page).
The models that the web api uses map my needs very well and I don't really have to change anything.
But should I simply bind to the model provided by the Web API? The risk I'm seeing is that if anything changes in the Web API, I might end up changing all over in my application. If I translate the web api model to my own in one place, I will only have to do changes there.
But on the other hand - mapping the Web API model to my own seems like a big unnecessary job, when the models will end up practically the same.
Keep things simple, introducing a mapping layer when you have control over both sides of the application seems unnecessary.
Only introduce extra complexity when it is required, for instance in our application we use asp.net w/ Nancyfx as our rest api. There are a few times we map from the api to models but those are specialized circumstances (model that contains data but also behavior).
One place where we used mapper was mapping for .net properties Pascal case to json properties camelCase.
But look at this blog post, even this can be fixed by providing a correct media formatter, and hence the mapping layer can be removed.
Mapping layer should be used for case by case basis. Hope it help you.
1 - Browser makes calls to WebAPI
2 - WebAPI returns JSON data - which is actually domain (or model) objects - replicas of database tables.
3 - Javascript translates those JSON objects into different objects depending on your presentation (presentations are always sophisticated - tables, graphs, lists, formated things, pivot tables).
4 - HTML is bound to those sophisticated javascript objects
You can find very beautiful examples here: upida4net.codeplex.com
with knockout and angular.

Resources