Service's read-only attribute

I am in need of a cache service to store data efficiently.

angular.module('core').service('markerCache', function(){
    var cache = [];
    this.set_cache = function(arr){
        cache = arr;
        this.cached = true;
    };
    this.cached = false; //this should be a read-only property, not a function
});

Additionally, I am looking to create read-only properties in Angular services (factory, service). If this is not directly possible, any workaround suggestions would be appreciated.
There is a way to define read-only properties in JavaScript, but I am curious about an Angular-specific approach.
By read-only, I mean the ability to set values inside the service only, for example:

angular.module('core').controller('Ctrl', function($scope, markerCache){
    markerCache.cached = false; //should not be able to be set outside of markerCache service
});

Update: Here is a functional service for those interested

angular.module('core').service('markerCache', function(){
    var cache = [];
    var cached = false;
    Object.defineProperty(this, "cache", {
        get: function() {
            return cache;
        },
        set: function(val){
            cache = val;
            cached = true;
        }
    });
    Object.defineProperty(this, "cached", {
        get: function() {
            return cached;
        },
        set: angular.noop
    });
});

Answer №1

Utilizing closure in JavaScript allows you to conceal a variable while making a property accessible using Object.defineProperty for reading the variable.

angular.module('core').service('markerCache', function(){
    var cache = [];
    var cached = false; // private variable
    this.set_cache = function(arr){
        cache = arr;
        cached = true;
    };
    Object.defineProperty(this, "cached", { // public readonly getter
      get: function() {
        return cached;
      },
      set: function(val) {
        //throw new Error('Cannot set internal cache state'); //throw custom exception
      }
      //set: angular.noop //or do nothing, empty setter
    })
});

Answer №2

Do you require assistance with AngularJS constants?

constant(name, value); This function is used to declare a constant service, which can be a string, number, array, object, or function, within the $injector. Constants can be injected into a module configuration function (refer to angular.Module) and they cannot be modified or replaced by an Angular decorator.

Answer №3

To avoid associating the variable with the this context, you can ensure its privacy by declaring it as var cached. Additionally, you should consider implementing a getter function within your service to retrieve the value of the cache, allowing consumers to access this value through the getter.

angular.module('core').service('markerCache', function(){
    var cache = [], 
        cached = false; //keep it private
    this.set_cache = function(arr){
        cache = arr;
        cached = true;
    };
    this.getCache = function(){
        return cached;
    }
});

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

Resolving Cross-Browser Issues with jQuery CSS Positioning on Hover of Div Elements

Struggling to create a jQuery interface that is functional across all browsers, although the current version should work on most Windows browsers. Check it out here: (Please keep in mind that the problematic part is kept minimal and the solution is expec ...

Keep the user on the current page even after submitting the parameter

I have a situation where I am loading a page into a specific div. This loaded page contains a link that includes a parameter which directs to another page for deletion. However, when I click on the loaded page within the div, it redirects me to the deletio ...

Customize the label and value in Material UI React Autocomplete

If you visit this link, you can see an example of what I'm trying to achieve. My goal is to have the option label and value be different from each other. In the provided example, the following code snippet is used: const defaultProps = { ...

Unable to escape the error indicators on Angular Material's MD elements in Visual Studio 2013

View Project ImageClick here for image description Having trouble with error marks on Angular material md elements in Visual Studio 2013 ...

Is it possible to incorporate some scripting to enhance the efficiency of deploying my mongoose database?

I'm completely new to setting up servers and diving into back-end development. My technical language is limited, making it challenging to find solutions through online research. I apologize in advance for my lack of expertise in this area. Currently, ...

Ways to display the values of angular variables within ng-bind-html

Converting HTML content from a database saved as varchar to front end JavaScript code can be tricky. The content is stored in a variable called vm.htmlContent and must be displayed as HTML on a web page. To achieve this, the ng-bind-html angular directive ...

What is the method for incorporating a variable into a fragment when combining schemas using Apollo GraphQL?

In my current project, I am working on integrating multiple remote schemas within a gateway service and expanding types from these schemas. To accomplish this, I am utilizing the `mergeSchemas` function from `graphql-tools`. This allows me to specify neces ...

Error: Failed to set the 'src' property of null when attempting to change the image source

When I click on an image, I want to change its source. Here is the HTML code: <div class="character"> <input id="1200" name="vocation_select" type="radio" value="1200" style="display: none" ></input> <label id="label_profesji" for="12 ...

Incorporate new content into a jquery mobile listview on the fly

I'm attempting to use JavaScript to dynamically populate a listview with items. Here is the code I have written: //Function to load data fields for items dynamically function initialiseFields(listViewId){ for(var i = 0; i < 10; i++){ ...

Customizing button appearances in the control div on Google Maps - A guide

Is there a way to manipulate elements and adjust styles by clicking buttons on the map control div? I want to achieve the same effect on the map as with the buttons in the table. Code: jsFiddle Update: Thanks to your assistance, I was able to achieve th ...

I could use some assistance with iterating through an array that is passed as a parameter to a function

Compute the product of parameter b and each element in the array. This code snippet currently only returns 25. This is because element a[0], which is "5", is being multiplied by argument b, which is also "5". The desired output should be ...

Please ensure that the table is empty before reloading data into it

I am facing an issue while binding data from the database. The data is being bound every 5 seconds, however, it does not clear the previous data and keeps accumulating. Instead of displaying just 3 rows when there are 3 in the database, it adds 3 rows ev ...

Utilize AngularFire to generate a new User and invoke the factory function to showcase notifications

I recently started working with AngularJS and wanted to integrate it with AngularFire/Firebase for storing project data. I created a factory that manages notifications to be displayed in a centralized location. Here is the structure of my factory: myApp.f ...

Using jQuery's AJAX function to send a POST request and extracting data from the response

Below is the jQuery AJAX call that I am using: $.ajax({ method: "POST", url: "/Agenda/Template", dataType: 'json', data: { "templateId": templateSelect.options[templateSelect.selectedIndex].value }, c ...

Internet Explorer does not automatically resend AJAX requests after submitting a form

Specifically mentioning IE in my title because my code functions correctly on Chrome. The "Maintenance" view I have is responsible for creating, editing, and deleting. The form is located in a partial view named "_MaintenanceForm" with its own GET/POST met ...

Sorry, but we couldn't complete your request: User verification unsuccessful: email must be provided

Every time I attempt to save a user's credentials to the mongo database, an error pops up saying: "User validation failed: email: Path email is required." I am clueless as to why this issue keeps happening. It only started occurring when I added the v ...

Tips for loading a fresh webpage while transferring data from an api

I have a page that displays a list of teams. When a team is clicked, I want to show the title and members of that team on another page. Right now, I have successfully loaded the teams in the list using this code: angular.module('my-app').control ...

The random quote generator or current tweet quote feature is malfunctioning

I am having trouble with a jQuery on click function that is not working to tweet the current quote. I am working on building a random quote machine and tweeting the current quote is essential. Despite successfully implementing the JSON API, I cannot seem t ...

Can a console application be created using AngularJS technology?

My task involves creating a console application that interacts with an API, modifies the data, and displays it on the console when a specific command is run. Is it feasible to achieve this using AngularJS? If not, what about utilizing Angular6 instead? To ...

Custom sample rate options in RecordRTC allow for the recording of silent audio tracks

I am currently working on implementing RecordRTC.js to capture audio from a microphone and then upload it to a server built with nancyfx. Initially, I am simply aiming to upload the audio stream and store it in a wav file for testing purposes. However, my ...