Created
December 8, 2014 23:56
-
-
Save eupharis/cd25a9f697355f4b085e to your computer and use it in GitHub Desktop.
Example of angular resolve with "class" resolve and ensuring data is current on every route change.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
"use strict"; | |
angular.module('JobListingApp') | |
.config(['$routeProvider', function($routeProvider) { | |
// ListingRoute "class" to ensure that all routes have | |
// current data in JobListings before they execute a route's controllers | |
var ListingRoute = function(params) { | |
angular.extend(this, params); | |
}; | |
ListingRoute.prototype.resolve = { | |
listings: ['JobListings', function(JobListings) { | |
return JobListings.ensure_current(); | |
}] | |
}; | |
// each route is an instance of ListingRoute, | |
// each has the same resolve property | |
$routeProvider | |
.when("/listings", new ListingRoute({ | |
templateUrl: "partials/listings.html", | |
controller: "ListingsCtrl" | |
})) | |
.when("/listings/:id", new ListingRoute({ | |
templateUrl: "partials/listing.html", | |
controller: "ListingCtrl" | |
})) | |
.otherwise({redirectTo: '/listings'}); | |
}]) | |
.factory('JobListings', ['$http', '$q', function($http, $q) { | |
var JL = {data: null}; | |
JL.ensure_current = function() { | |
var self = this, | |
data_deferred = $q.defer(); | |
if (self.data) { | |
// for every call after the first call, | |
// promise is resolved immediately | |
data_deferred.resolve(self.data); | |
} else { | |
$http.get('/api/job-listings').success(function(data) { | |
self.data = data; | |
// promise is resolved after API GET | |
data_deferred.resolve(data); | |
}).error(function() { | |
//redirect someplace? authorize? | |
}); | |
} | |
// promise is immediately returned | |
// route controller will not execute until promise is resolved | |
return data_deferred.promise; | |
}; | |
return JL; | |
}]) | |
; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Why go through the process of creating a class, constructor and then using prototype? Why not put the listings method right on resolve? Is there some sort of perf benefit?