I have an Angular service that either should return an existing object or call a webservice and load some data. To have a consistent client API I want to use a promise in both cases.
It’s not very hard to do this using Angular:
This file contains 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(app){ | |
var dataService=function($q,$http){ | |
var getData=function(fromCache){ | |
if(fromCache){ | |
return $q.when({data:[{Id:1, Name:'Product X'},{Id:2, Name:'Product Y'}]}); | |
} | |
else{ | |
return $http.get('http://sampleserver/api/products'); | |
} | |
}; | |
}; | |
app.factory('dataService',['$q','$http',dataService]); | |
}(angular.module('sampleApp'))); |