AngularJS getting data from backend - angularjs

I would like to know what is the proper way to get data from backend when I want to use angularJs (or similar) in my web app?
The only way I see is to render html (static html with js scripts - e.g. angularjs) with no data from backend and then download data via ajax requests from my backend API. But I think this solution is not good because of many HTTP requests:
For example I have blog website, I want to show a post, comments, and the related posts on the sidebar. So probably I need to make at least 3 HTTP requests to get the data unless I will prepare API to get all I need in one request.
I can also imagine websites that could have much more HTTP requests. Is it a proper way to do this? Doesn't it overload a server? Or my way of thinking is so wrong?

It is either websockets or HTTP requests. Preparing API to get all in one request is one option. Another two options are XMLHttpRequest/iframe streaming which is a method of a technique known as Comet.
I would go with websockets since it is supposed to solve the problem that was previously solved with weird applications like iframe streaming. There are libraries that properly handles fallbacks if the browser does not support websockets:
web-socket-js ( this needs a websocket server )
Socket.IO ( this has a node.js module and also implements a kind of unnecessary protocol on top of websocket protocol )
If you choose the old methods there will be many problems waiting for you on the road like XmlHttpRequest.responseText while loading (readyState==3) in Chrome

I think you have to distinguish two cases:
You render the page for the first time.
You update parts of your page when something changes
Of course in the second case it makes sense to fetch only parts of the page via individual HTTP requests. However, in the first case you can simply serialize your complete model as one JSON object and embed it in the page like this:
<script type="text/javascript">
var myCompleteModel = { /* Here goes your model */ };
<script>
The controllers of the components on your page can then access this global variable to extract the parts being relevant for them. You can also wrap access to the initial model in a service to avoid accessing a global variable in all your controllers.

Related

best practice to pass mock data to Angular & Ionic

I am working on an Ionic phone app using AngualrJs as the framework. Now I faced an issue. I don't want my app to send an HTTP request to my backend(which use Ruby on Rails) API to do a manual test.
So I'm wondering what's the best practice to pass a mock JSON data as a response when I want to call the API.
I'm not familiar with Angular and Ionic, I can find some tutorials on both sides but I don't know what's is the best practice if use them together.
You can either store the data in localStorage after the first hit and read the data from localStorage every-time whenever you need.
https://medium.com/#petehouston/awesome-local-storage-for-ionic-with-ngstorage-c11c0284d658
Or you can use
$httpBackend
https://docs.angularjs.org/api/ngMock/service/$httpBackend
by saving json files locally and injecting them back when the application tries to hit the network . One limitation here, you cannot update the json file later after the user have installed the application.
So, localStorage is preferred if you want to cache the data you have received from network.

What is the best way to route to different controllers in CakePHP depending on HTTP header values?

I'm looking for a way to route URLs to different controllers depending on the value of the HTTP 'Accept' header.
All I have found so far is the official CakePHP documentation on routes but it is not very detailled.
Is this possible using route configurations or do I have to do this another way (e.g. by implementing a DispatcherFilter to inspect the CakeRequest)?
I want a set-up where I can seamlessly distribute responsibilities
between server side and client side: e.g. letting the client handle
the view creation instead of the server responding with an HTML
document.
Guess you're using something like AngularJS? Well, then you expect a data format back instead of HTML I guess. So request application/json via the accept header and / or the extension. Cake can detect both and respond accordingly.
Read about JSON and XML views in the manual.
http://book.cakephp.org/2.0/en/views/json-and-xml-views.html

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.

How to create a dynamic front end based on Node JS, MongoDB, Sails JS

Basically I'm writing an app and am using Sails, MongoDB and Node JS for the back end. I'll use Sail's API features and was wondering what would be the best way to make the app realtime.
For instance I could use AJAX to call the API and manipulate the DOM using jQuery and update the DB through $.post then let the model update the db in the backend, however I'm finding this approach quite cumbersome. Not to mention I can see the code could become quite difficult to maintain after a while.
I've been doing some research and - if I understood correctly - it seems I could use either Backbone, Angular or Knockout to manipulate the data/DOM on the front end, however I'm not sure what would be the best approach in my case nor whether any of these would indeed suit my needs:
Being able to get the data dynamically
Update the data and the DOM dynamically as the user interact with the page
Post the updated data dynamically with none or as minimal data transformation on the back end as possible
All the above asynchronously
As I don't want this to become a heated debate on which library is best, so I would like to know only whether any of the aforementioned libraries can do what I need and which is the leanest/simplest/has the lighter learning curve.
I did similar research a while ago and when found AngularJS, just stopped looking any further.
Right to your questions:
Being able to get the data dynamically
It is pure pleasure to do it in Angular. For the very basic functionality you have got $http service which allows you to send http request and register a callback when the data arrives.
For more complicated things there are modules ngResource and Restangular (external).
Update the data and the DOM dynamically as the user interact with the page
For manipulating DOM, Angular introduced concept of directive. It is basically future of the web (Shodow DOM and Web Components) right now. At this time point, there is nothing more elegant out there.
Post the updated data dynamically with none or as minimal data transformation on the back end as possible
Yes. JSON.
All the above asynchronously.
Yes, of course.
SailsJS provides interchangeability of HTTP or socket.io connections. In your case I think sockets would be a better fit than AJAX.

how to send/receive data securely in backbone.js

I have created RESTFUL urls that respond with some JSON data when fetched by backbone.
So a url like /lists responds with a json array of user-created lists. My want that if the url is accessed by address bar input like mydomain.com/lists, the json data is displayed in text on browser. I want the server to respond only if the url is accessed from within the application. Can somebody provide me some hints on how to achieve this?
Like #Thilo said, you're not going to be able to do prevent a person with the right tools to see what's coming across the wire, Firebug's console/net tabs already keep track of requests and show the contents of responses.
That being said, what you can do is check whether the HTTP_X_REQUESTED_WITH HTTP header is set to 'XMLHttpRequest', and only return the JSON in this case. Backbone makes an Ajax call so this will always be the case with the Backbone calls (in modern browsers). Again this won't help much except for people who type it into the address bar directly (and do a normal GET request) won't see the JSON.

Resources