Is there an Angular Profile service offering getter and setter properties?

Can a singleton Angular service be created with getters and setters along with logic implementation? I was provided with the following code snippet and tasked with replicating it in an Angular service. Although it may seem straightforward, I'm finding it quite challenging:

public class Profile 
{
    private AuthSvc _auth = new AuthSvc();

    private string _userId = null;
    private string _displayName = null;

    public string UserId
    {
        get 
        {
            if (_userId != null) { return _userId; }
            _userId = AuthSvc.getUserId();
            return _userId; 
        }
    }
    public string DisplayName
    {
        get 
        {
            if (_displayName != null) { return _displayName; }
            if (_userId == null) { return null; }
            _displayName = AuthSvc.getDisplayName(_userId);
            return _displayName; 
        }
        set (string value) {
            if (value == null && value.trim().length < 1) { return; }
            if (_displayName != null && _displayName == value.trim()) { return; }
            _displayName = value.trim();
            AuthSvc.setDisplayName(_userId, _displayName); 
        }
    }

}

Here is my failed attempt before I broke down in tears:

(function () {

    'use strict';

    angular
        .module('myapp')
        .service('Profile', ProfileService);

    ProfileService.$inject = ['common', 'dataService'];
    function ProfileService (common, dataService) {

        var userInfo = {
            id   : '',
            name : ''
        };

        var service = {
            id : $get getUserId(),
            name : $get getUserId(), $set(value, setUserId);
        };

        return service;
        /////////////////////////

        function getUserId () {
            if (!userInfo.id) { userInfo.id = common.getUserId(); }
            return userInfo.id;
        }

        function setName (value) {

        }

        function getName () {
            if (userInfo.name) { return userInfo.name; }
            var userId = getUserId();
            if (!userId) { return ''; }
            dataService.users.getDisplayName(userId).then(function(name){

            });
        }

    }

})();

Answer №1

Your implementation of the service is currently set up as a factory.

In Angular, a service uses this for properties, while a factory returns an object.

You can easily transition your component from a service to a factory:

angular
    .module('myapp')
    .factory('Profile', ProfileService);

Make sure to pass function and object variable references to the returned object:

var service = {
        userInfo  : userInfo ,
        getUserId :  getUserId,
        getName : getName 
    };
// or 
service.myfunc = someNamedFunction;

If you prefer to keep it as a service, simply switch all variables to be members of this.

Answer №2

Indeed, the service is essentially an ordinary object that can be manipulated using Object.defineProperty. I prefer to use the factory syntax.

(function () {
    'use strict';

    angular.module('mymodule', [])
        .factory('myService', function () {
            var service = {};
            var userInfo = {
                 id   : '',
                 name : ''
            };
            serivce.getUserInfo = function(){ return userInfo;};

            var myPropertyPrivateVal;
            Object.defineProperty(service, 'myProperty', {
                get: function () { return myPropertyPrivateVal; },
                set: function(value) { myPropertyPrivateVal = value; }
            });

            return service;
        });
})();

You're all set and good to go :)

The main difference when opting for the service syntax is that you would use this instead of initializing an object with var service = {};

(function () {
    'use strict';

    angular.module('mymodule', [])
        .service('myService', function () {
                var userInfo = {id : '', name : '' };
                this.getUserInfo = function(){  return userInfo;};

                var myPropertyPrivateVal;  
                Object.defineProperty(this, 'myProperty', {
                    get: function () { return myPropertyPrivateVal; },
                    set: function(value) { myPropertyPrivateVal = value; }
                });
        });
})();

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

What could be causing my Vue component to not refresh?

Can anyone help me figure out why this component isn't re-rendering after changing the value? I'm attempting to create a dynamic filter similar to Amazon using only checkboxes. Here are the 4 components I have: App.vue, test-filter.vue, filtersIn ...

The cropper fails to load within the image element inside a modal pop-up

Utilizing fengyuanchen's cropper library, I am cropping an uploaded image and then submitting it to a form. <div id="change-dp" uk-modal> <div class="uk-modal-dialog uk-modal-body"> <button class="uk ...

Angular sending information from one page and retrieving it on another

The reportForm page allows users to input information and submit it to create a report. reportData = { headline: $scope.headline, fromDate: $scope.fldFromDate, toDate: $scope.fldToDate, whatever: $scope.whatever } $http.post(reportUrl + $scope.repor ...

Updating parent array values within child components in React

Currently, I am working on a React application where I need to save the handlers for all windows opened from the app. Previously, before using React, I stored these windows in a global array attached to the parent window, although I understand that using J ...

The scrolltop function is dysfunctional on CentOS operating systems

I'm currently working on implementing smooth scrolling functionality when a button is clicked. The feature works perfectly fine with a local Apache server and IE10+, but when the project is deployed on "CentOS", it doesn't work on the same browse ...

How to highlight all the text within a 'pre code block' when double-clicked using JavaScript

Is there a way to make code blocks on my blog automatically selected when double-clicked without using jQuery? Here is the code I have so far: I apologize if this is a silly question, I am still learning! <script type="text/javascript" src="https://c ...

What is the best way to determine the total number of rows that have been generated by the Asp:Repeater?

I'm looking for a way to retrieve the total number of rows generated by the repeater control using either Javascript or JQuery. Can anyone help me with this? ...

How to eliminate blinking in Ajax refresh upon successful completion

I have come across this issue, and although I've checked out a solution on Stack Overflow (ajax refresh - how to remove the blinking), it hasn't resolved my problem. Is there a way to prevent the page from blinking every 3 seconds when the Ajax ...

Having trouble with d3 / svg layering when introducing new nodes overtime

Struggling with a frustrating issue on my d3 force directed map project. Initially, I render the necessary nodes and links, then periodically check for updates through AJAX. The problem arises when adding new nodes and links – they appear over existing c ...

Leveraging jQuery or javascript to display json data in a table with multiple columns

My goal is to convert a JSON data into an HTML table that dynamically creates columns based on the content of the JSON. However, I am facing challenges in looping through the JSON and rendering multiple columns when necessary. The desired output for the e ...

AngularJS ng-repeat is not updating when the state changes

Seeking assistance with an Angular application challenge I'm facing. I have implemented a ng-repeat in my app to display the latest messages stored in an array within a controller named "comunicacion": ng-repeat in comunicacion.html <div class=" ...

Scrolling automatically to the first empty mandatory field with the help of AngularJS

After utilizing angular js to create a form with 7 input elements, I encountered an issue. Upon clicking submit, the form should scroll up to the first blank required field. However, it is not accurately identifying the left blank field. Any suggestions on ...

"Trouble with Angular's http.get method failing to retrieve data from MySQL through Node

I am struggling to retrieve data from MySQL using Angular and Node.js. Despite trying, I am unable to make it work. When I check Postman using the link http://localhost:8080/locations, I can see the data. { "status": "200", "items": [ { "cit ...

Discover the best approach for transforming a complicated JSON object/array into a map using inheritance coding techniques

Could someone help me with creating an array of objects (only 1 level) based on the following JSON structure? [ { 'family' : { 'name' : 'Doe', 'from' : 'Foo' }, ...

Tips for expanding frisby.js by adding new "expect" functionalities?

Looking to enhance the Frisby.js module with custom expect methods without altering the source code. These extensions are tailored for my REST API to streamline common tests into a single method. An issue arises as the Frisby.js module exports its methods ...

Retrieving width and height of the content block inner in Framework7, excluding navbar and toolbar dimensions

Is there a reliable way to determine the width and height of the page content-block-inner, excluding the navbar and toolbar? This measurement can vary across different devices and operating systems. I attempted to assign an id to the content-block-inner a ...

Combining the power of Visual Studio Code with NodeJs allows for seamless detection of missing package namespaces

Recently, I've encountered a frustrating problem. It occurs when: I create a new Node project without any installed modules I use import '' and press ctrl+space between the brackets, resulting in unnecessary inferred namespaces. Alth ...

Choose the parent element along with its sibling elements

How can I target not only an element's siblings but also its parent itself? The .parent().siblings() method does not include the original element's parent in the selection. $(this).parent().addClass("active").siblings().removeClass("active"); I ...

Numerous JQuery AJAX form submissions leading to individual outcomes

I have implemented a script on my page that handles form submissions for multiple forms by calling a specific action. Here is the script: $(function () { $('form').submit(function () { if ($(this).valid()) { $.ajax({ ...

Problem encountered when trying to use the sharp package in NuxtJS

I attempted to implement this code in my Nuxt project, but it encountered an issue during compilation. Within my plugin/sharp.js file: import vue from "vue" import sharp from "sharp" vue.use(sharp) And in my nuxt.config.js file: plugi ...