Follow by Email

Angular 2 - Data persistence


While building client-side apps, your intent is typically to work with some kind of data in a read-write fashion. So you end up needing a way to pull and process data from Javascript in the client. This is handled in a couple of different ways with Angular, depending on the source of your data. 

If you are only concerned with storing data for the time in which the user is using your application, you could store that data in memory. 



Angular's dependency injection makes this fairly trivial to do. You can create a Javascript class or object to store your data, provide it to your app as something that can be injected in, and then do constructor injection where needed to bring in the instance of that object. From there, you can do read-write updates to that object and have the changes available throughout. 



To work with data stored in browser storage, such as local storage, you will find the need to write your own Javascript code to do so, and then use it with the services pattern, leveraging Angular's dependency injection to work with it throughout your application. If you are looking to work with data from the server via an API, Angular has some built in framework stuff to help you with that. One way you can process data to and from an API is by leveraging the HTTP protocol. You can do this in two ways. 



One, by using the XML HTTP request or XHR and the other by using JSONP.
Angular provides an HTTP module in the framework for abstracting out working with the way XHR and JSONP calls are done via client script. So you can do things like make GET and POST calls that work with JSON data as simple as passing a URL and a Javascript object to an Angular HTTP function and subscribing to the results.