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', [])
// UPDATED: A service to cache a promise
// representing a request to a web server
.service('myResource', function myResource($http, $rootScope) {
var promise;
var timesRequested = 0;
var timesCalled = 0;
return {
get: function(){
timesCalled++;
if (!promise) {
// A promise has not been created. So the request to the
// server has not yet been made. Send the request now.
timesRequested++;
var url = 'http://jsonplaceholder.typicode.com/posts/1';
promise = $http.get(url);
}
// Now, there is definitely a promise for a request that is
// either in flight, or completed.
$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;
});
})