Using AngularJS $resource as a "service" with flexible base URL

A custom JS library based on Angular includes various services for clients, structured like so:

angular.module('Services', [
    'ngResource'
]).factory('UserService', function($resource) {
    return function(whatsonUserId) {
        return $resource('/rest/user/:action');
    }
}. factory ...

Clients can easily incorporate the library by doing the following:

app.controller('Ctrl', function(UserService) {
    ...
    UserService().doSomething()
}

However, since clients host their HTML on their own URLs, the root URL for MY services is incorrect. To address this, an absolute URL must be supplied to $resource:

return $resource('www.my.server.url/rest/user/:action');

But there are multiple server URLs - staging, development, production environments - some specific to each client.

The query at hand: Is it feasible to implement a generic 'service' where users of the library can define the 'server root' for 'Services'?

Answer №1

Utilizing the provider API presents a practical use case. By employing the module.provider, you have the ability to define your own API. This can be achieved by creating a provider for configuring your server, as demonstrated below:

module.provider('serverConfig',function() {
    var serverUrl='val';     //default url
    this.setServerUrl=function(url) {
       serverUrl=url;
    };
    this.$get=[function(){
       return {url:serverUrl};
    }];
})

After establishing your configuration service, it can be integrated into any individual services that may require it. A sample implementation is shown in the following code snippet:

factory('UserService', function($resource,serverConfig) {
    return function(whatsonUserId) {
        return $resource(serverConfig.url+'/rest/user/:action');
    }

The provider setup must occur during the configuration stage of your application, similar to how it's done below:

myApp.config(["serverConfigProvider", function(serverConfigProvider) {
  serverConfigProvider.setServerUrl('serverUrlstring');
}]);

Answer №2

In newer versions of AngularJS, such as 1.4.3, the code snippet below demonstrates how to create a UserService factory that can handle different subdomains:

.factory('UserService', function($resource) {
  // Default subdomain is set to 'www'
  return $resource("http://:subdomain.my.server.url/rest/user", {subdomain: 'www'});
})

With this setup, users have the flexibility to call the service with a specific subdomain or without one:

UserService.query({subdomain: 'user001'}).$promise.then(
// => http://user001.my.server.url/rest/user

or

UserService.query().$promise.then(
// => http://www.my.server.url/rest/user

This approach allows for static or dynamic subdomains, catering to various use cases.

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

Having an issue with my Typescript code that is throwing a "Uncaught ReferenceError: angular is not defined" error

I am currently in the early stages of learning typescript with angularjs through online video tutorials. I have encountered an issue while attempting to include the angular module in my "app.ts" file, which serves as the main file in the backend. Below is ...

Issue with Angularjs not saving data in a specific field

I've encountered an issue trying to save data in the name field. Even though the POST request runs without any errors, the MongoDB collection only shows the _id and _v fields being updated. To put it simply, I'm unable to successfully save data ...

Prevent the onClick function of the outer div from being triggered by clicking on the inner div

Similar Question: Stop parent container click event from firing when hyperlink clicked My issue is <div onClick="someJScode();"> ... <div></div> ... </div> I need to prevent someJScode() from executing when the inner di ...

Utilizing Vue.js i18n for a multi-line text display

Currently, I am implementing i18n single file component in order to provide translation support for my application. In order to achieve this, I have been utilizing the i18n tag as shown below: <i18n> { "fr": { "text": "Lore ...

JavaScript does not function properly when interacting with the result of a POST request made through $.ajax

Question: After including jQuery files and functions in index.php, do I also need to include them in select.php? To clarify my issue, here is the problem I am facing: Initially, I am trying to send data to select.php using jQuery's $.ajax. The data ...

Error encountered in a pre-existing project due to Vuetify configurations

Having trouble downloading Vuetify 3 onto my Vue 3 app, I keep encountering an error. Despite attempting to use 'npm install --save @popperjs/core vuetify/styles', it's still not working as expected. I'm curious to understand the root c ...

Showing PHP array in the JavaScript console

I have a straightforward AJAX script that sends 3 variables to an external PHP script. The external script then adds them into an array and sends the array back. I want to output this array in the JavaScript console to check if the variables are being pass ...

What is your approach to managing route-specific URLs?

Imagine a scenario where we have a group of entities, such as articles, and we want to create a list with links to specific articles. If we were not using angularjs, our list item code could look something like this (twig): <li> <a href="{{ ...

The JSON data retrieved from the API is showing as undefined for the property

Currently, I am working on a project that involves utilizing the Shopify API to fetch products and related data from a store in JSON format. While I was able to successfully retrieve the JSON object from the API, I encountered an issue when trying to acces ...

`Is it possible to retrieve Wikipedia information directly from a Wikipedia link?`

Is there a way to create a feature where users can input a Wikipedia page link and retrieve all the text from that page? I am working on adding a functionality to my website where users can paste a link to a Wikipedia page they want to analyze into an inp ...

The index on ref in MongoDB does not seem to be yielding any improvements

I've encountered a performance issue with my model: const PostSchema = new mongoose.Schema( { _id: mongoose.Schema.Types.ObjectId, workSpace: { type: mongoose.Schema.Types.ObjectId, ref: 'Workspace&apos ...

Using the html5 file reader API in JavaScript to retrieve a file as a binary string and then sending it through an ajax request

I'm attempting to obtain the binary string of files, but I seem to be unable to do so. Why does readAsDataUrl work while readAsBinaryString doesn't? I have posted my code on jsbin and any help would be greatly appreciated. Thank you. Check out ...

The performance of the Firefox browser is being compromised by a sluggish web page

After clicking the save button, a message appears only in Firefox browser stating: "A web page is slowing down. What would you like to do?" https://i.sstatic.net/XrnH5.png ...

Javascript Parameter

Each time I enter scroll(0,10,200,10); into my code, it seems to output the strings "xxpos" or "yypos" instead of the actual values. I attempted to remove the apostrophes around them, but unfortunately, that did not resolve the issue. scroll = function( ...

Incorporating interactive buttons within Leaflet popups

I'm facing an issue with adding buttons to a Leaflet popup that appears when clicking on the map. My goal is to have the popup display 2 buttons: Start from Here Go to this Location The desired outcome looks like this sketch: ___________________ ...

What is the best way to trigger a re-render of a Vue component after a change in Vuex

I'm interested in developing a custom component to modify the basemap of a leaflet map without relying on L.control.layers. To achieve this, I created a sidebar component that offers options to switch between different basemaps. In my implementation, ...

What methods can be used to pause a jQuery function when hovering and resume it when the mouse leaves?

I'm currently working on a jQuery function that operates on the mousemove event. The goal is to have two images - one main image and one shadow image, with the shadow image reflecting movement based on mouse position. While everything is functioning p ...

Experiencing difficulty uploading several image files using ng-file-upload

Here is the HTML code I have: <div class="col-md-6"> <img ngf-src="!picFile.$error && picFile" style="height: 150px; width: 200px;"> <input type="file" ngf-select ng-model="picFile" name="file" accep ...

The recursive JavaScript function is not returning as expected when using defer

Having an issue with a recursive function. It appears to loop through effectively when the data return is null, but it fails to return the promise correctly when the data is not null after completing the recursive task. It seems like the promise gets los ...

A different approach to calling JavaScript functions

I have a method that populates an array. I would like to utilize it in this manner: arrayname.fill("First Array"); And not like this: arrayname = fill("First Array"); What approach should I take? function fillArray(name) { let newArray = ...