I am working with AngularJS framework (noobie), and I am trying to develop a service String
which has to merge 2 resources. I mean merge the result (json) of 2 requests:
It works great when string-'+language+'/:stringId.json exists. But when is doesn't exist an error 404 is displayed in the console as I expected but the return of String.get(...) is empty.
Service.js
angular.module(...)
.value('Language', 'fr')
.factory('String', ['$resource', 'Language',
function($resource, language){
return jQuery.extend(
$resource('string/:stringId.json'),
$resource('string-'+language+'/:stringId.json')
);
}])
Controllers.js
angular.module('exBusiApp.controllers', [])
.controller('LayoutCtrl', ['$scope', 'String',
function($scope, String, version) {
$scope.string = String.get({stringId: "layout"});
}])
What I would like : in my controller call a service which return strings needed (stringId parameter) in the current language (the controller doesn't have to matter about language, service take care of that). SO to do that I need a Services which merge the result of 2 json files (on for default strings and and other for specific language, the default is used if some string in good language json are missing). So that my idea to merge the 2 resources.
And it works well when the 2 files exist. Ex : en {hello : "hello, mistake : "mistake"} fr {hello : "bonjour"} the view is able to display bonjour and mistake (as mistake is not defined in french file)
If someone has an idea, would be grateful.
You can do this easier without $resource
:
angular.module(...)
.value('Language', 'fr')
.factory('String', ['$http', '$q', 'Language', function($http, $q, Language){
return {
get: function(stringId){
var deferred = $q.defer(),
intermediate = $q.defer(),
generic = $http.get('string/' + stringId + '.json'),
specific = $http.get('string-' + Language + '/' + stringId + '.json');
specific.then(function(data) { intermediate.resolve(data); }, // Success
function() { intermediate.resolve({}); }); // Error
$q.all([generic, intermediate.promise]).then(function(results) {
deferred.resolve(jQuery.extend(results[0].data, results[1].data));
});
return deferred.promise;
}
}
}]);
This uses plain $http
with two promises. To allow the first request to fail, it resolves another (intermediate) promise, which always succeeds.
The intermediate promise and the second request's promise are then resolved, combined and the resulting new promise is resolved with the result in the end. You can use it in your controller like this:
angular.module('exBusiApp.controllers', [])
.controller('LayoutCtrl', ['$scope', 'String',
function($scope, String, version) {
$scope.string = "";
String.get("layout").then(function(result) {
$scope.string = result;
});
}]);