AngularJS, the innovative tool that combines two separate resources into a single cohesive service

Exploring the AngularJS framework as a beginner, I am currently working on creating a service called String that merges the results of two resource requests. The first request is to string/:stringId.json, and the second is to

string-'+language+'/:stringId.json
.

Everything works smoothly when the string-'+language+'/:stringId.json exists. However, if it doesn't exist, an expected 404 error is displayed in the console, but the return value of String.get(...) ends up being 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"});
    }])

I envision calling a service in my controller that retrieves necessary strings based on the provided stringId parameter in the current language without the controller worrying about the language specifics. This leads me to the concept of merging the results of two JSON files (one for default strings and another for specific languages where defaults are used if translations are missing). Hence, the idea to merge the two resources.

When both files exist, like for example having English {hello : "hello, mistake : "mistake"} and French {hello : "bonjour"}, the view displays "bonjour" and "mistake" (as "mistake" is not included in the French file).

If anyone has any insights or suggestions, they would be greatly appreciated.

Answer №1

To achieve this task more efficiently, you can bypass using $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 approach utilizes plain $http along with two promises. It accommodates the possibility of the initial request failing by resolving an additional (intermediate) promise that always succeeds.

The intermediate promise and the promise for the second request are both resolved, then combined. The resulting new promise is eventually resolved with the aggregated result. This functionality can be incorporated into your controller in the following manner:

angular.module('exBusiApp.controllers', [])

.controller('LayoutCtrl', ['$scope', 'String',
    function($scope, String, version) {
        $scope.string = "";

        String.get("layout").then(function(result) {
          $scope.string = result;
        });
    }]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

A dynamic Angular search box designed for filtering columns in a table

I have a functioning table code that displays data related to domains: Now, I would like to enhance this table by adding a dynamic search box specifically for filtering the column named domain. As the user types in new characters in the search box, the ta ...

In Java, use an HttpRequest to retrieve the webpage content and ensure that the process waits until the JavaScript has finished

Is there a way in Java to wait for partial content of a webpage to be loaded by JavaScript before initiating the rest of the process? The webpage contains script that loads additional content once the page is fully loaded, and I need to ensure that the p ...

What is the best way to incorporate a function into a jQuery event?

When the mouse is moved over images, I want to trigger a function that performs a specific action. However, I am unsure of how to write the code to achieve this. function reload(){ $("img.lazy").lazyload({ effect : "fadeIn", event ...

The argument type of '() => JQuery' cannot be assigned to a parameter type of '() => boolean'

Having trouble writing a jasmine test case for my method due to an error: spec.ts(163,18): error TS2345: Argument of type '() => JQuery' is not assignable to parameter of type '() => boolean' Any suggestions on how to resolve ...

Developing a personalized data binding feature with AngularJS and utilizing ng-repeat

Looking to design a unique controller that can display multiple similar objects connected to a dataset structured like this: [{name: card1, values: {opt1: 9, opt2: 10}},{name: card1, values: {opt1: 9, opt2: 10}}] The goal is to showcase the name and one ...

The navigation bar is malfunctioning on Bootstrap 4.0.0-beta.2 framework

I have recently updated to the latest version of Bootstrap: "@ng-bootstrap/ng-bootstrap": "^1.0.0-beta.5", "bootstrap": "^4.0.0-beta.2", "core-js": "^2.4.1", "jquery": "^3.2.1", "popper.js": "^1.12.9", As part of this update, I incorporated a navbar: &l ...

What is the best way to remove an item from my online shopping cart using JavaScript?

I am currently developing an online store website. One issue I am facing is deleting items from the cart after a customer completes an order. Below is the array of cart items: const products = [ { id: '0', name: 'Nike Slim Shirt&ap ...

custom dialog box appears using ajax after successful action

Recently, I created a custom dialog/modal box with the following code: <div id="customdialog" class="modal"> <div class="modal__overlay"></div> <div class="modal__content"> <h2><strong>Hello</strong&g ...

How come my uvmapped texture is flipping vertically when using iewebgl + threejs?

Currently in the process of developing a 3D viewer for game pads with the aim of customizing the pad using various colors and materials. Initially, I created a simple ".bin .js" loader with sample materials using Threejs r62 to create a visualizer prototy ...

Using MaterialUI to create a GridListTile with two IconButtons

I'm working with a GridListTile and trying to add a second button, but I'm having trouble getting both buttons to display. Even though I've attempted to include two ActionIcons, only one of them is showing up. Here's the code snippet: ...

The LinkButton feature is not functioning correctly in combination with the showmodaldialog

What is the best way to open a window.showModalDialog with a link button when updating a form? I have a link button on my form that updates data. When the client's status becomes active, I want to open a window for additional information entry. Pub ...

Setting the error name in an extended Error class in Node.js: A step-by-step guide

My goal is to assign the error name as err.name = 'ExpressValidatorError'; within a custom Error class called class AppError extends Error that is then passed to centralErrorHandler for filtering and handling errors based on err.name. Despite ...

Having trouble integrating Animate.css with AngularJS version 1.3

As per multiple online sources, this method is said to be effective. <li ng-animate="{enter: 'animated shake'}" ng-repeat="name in names | filter:search"> <a href="#"> {{name}} </a> </li> You can view the Plunkr exampl ...

Switch or toggle between colors using CSS and JavaScript

Greetings for taking the time to review this query! I'm currently in the process of designing a login form specifically catered towards students and teachers One key feature I'm incorporating is a switch or toggle button that alternates between ...

Closing the Angularstrap dropdown when clicking elsewhere

Is there a method to close an angularstrap dropdown only when clicking outside of it? The current behavior is that it closes when you click inside the dropdown. Thank you ...

What is the best way to find a specific string within an array of strings?

I have a list of tasks as strings: todo=[ 'Get up', 'Brush my teeth', 'Go to work', 'Play games' ]; I am attempting to compare it with this: Template: <input (input)="checkArrays($event)" /> In my ...

Inquiries regarding the vuex dynamic registration module result in a complete refresh of all Vue components

When trying to create a new Vue component, I encounter the issue of having to call store.registerModule() before creation. However, this action results in all existing Vue components being destroyed and recreated. The same issue happens when using store. ...

Slicing an array in Javascript/Angular before it is officially initialized

Is it possible to specify the portion of an array to retrieve before making a $http GET request in Angular? I am aware of slicing arrays, but wondering if I can set this up in advance for better performance. In PHP, you can do something similar, but not ...

Obtaining an element through its id using an expression in an Angular directive

Here's a complex question that needs to be broken down. I'm trying to mimic the behavior of the native <label> for <input>. Since nesting is not an option, I use a style like this: <input type="checkbox" id="test" /> Some other ...

What is the best method for retrieving information from Google Firestore and integrating it into my Vue component?

In the process of creating a game lobby where one player initiates a game and waits for another player to join. Once the second player joins, the Firestore document containing information about the game is updated with the player's name stored in the ...