JSFiddle - React, Tailwind, and code Playground
by PeterShafer
HTML
<div ng-app="angularApp">
<div ng-controller="Demo1 as demo">
<h1>{{ demo.data.title || 'title unavailable' }}</h1>
<p>{{ demo.data.body || 'body unavailable' }}</p>
<hr>
<h2>The myResource service has...</h2>
<ul>
<li>...made HTTP calls <em>{{ timesRequested || 0 }}</em> times.</li>
<li>...been called <em>{{ timesCalled || 0 }}</em> times.</li>
</ul>
<h2>Call the service again...</h2>
<p>
<button ng-click="demo.clear()">Clear Data From Controller</button>
<button ng-click="demo.call()">myResource.get()</button>
</p>
</div>
<hr>
<div ng-controller="Demo2 as demo">
<p ng-show="demo.data">Data from the server is held in the cache!</p>
<p ng-show="!demo.data">There is no data from the server held in the cache!</p>
</div>
</div>
JavaScript
angular.module('angularApp', [])
// A service to cache data from a request to a web server
.service('myResource', function myResource($http, $rootScope, $q) {
var cached_data;
var timesRequested = 0;
var timesCalled = 0;
return {
get: function(){
var promise;
timesCalled++;
if (!cached_data) {
// The service hasn't yet cached any data.
// Make a request to the server.
timesRequested++;
var url = 'http://jsonplaceholder.typicode.com/posts/1';
promise = $http.get(url);
promise.then(function(response){
cached_data = response;
});
}else{
// The service has already cached data from the server.
// Wrap cached data in promise and return.
promise = $q.when(cached_data);
}
$rootScope.timesRequested = timesRequested;
$rootScope.timesCalled = timesCalled;
return promise;
}
};
})
// This first controller will handle button presses.
.controller('Demo1', function demo($rootScope, myResource) {
var self = this;
var call = function(){
myResource.get().then(function(response){
self.data = response.data;
});
};
this.call = call;
call(); // Check for relevant data immediately.
this.clear = function(){
self.data = {};
};
})
// This second controller will display the status of the cached data.
.controller('Demo2', function demo($rootScope, myResource) {
var self = this;
// Check for relevant data immediately.
myResource.get().then(function(response){
self.data = response.data;
});
})