Building an AngularJS Service with TypeScript that is Non-Singleton: A Step-by-Step Guide

I need help converting an AngularJS Typescript Service into a Non-Singleton. Can anyone provide guidance on how to achieve this? (Note: This is not the same as other questions that focus on achieving this in JS) I have included some simple pseudo code below:

class TestService {

    private message: string;

    constructor() {
        this.message = 'Hello!';
    }

    greet() {
        console.log(this.message);
    }
}

angular.module("app").service("TestService", TestService);

Answer №1

Consider transforming your service from being provided at the module level to the component level.

Here's an example:

@Component({ selector: 'my-component', template: my-component.html, providers: ['myService'] })

Answer №2

When it comes to having a shared object across a component hierarchy, using services as singletons is not the way to go. Instead, you can utilize requires to access an instance of a parent component and have the shared object linked to that component's controller.

angular.module('app', []).component('parentComponent', {
  template: 'Parent<br><ng-transclude></ng-transclude>',
  transclude: true,
  controller: function() {
    this.sharedData = {
      rnd: Math.random() * 10
    };
  }
}).component('childComponent', {
  template: 'child {{ $ctrl.parentCtrl.sharedData.rnd }}',
  require: {
    parentCtrl: '^parentComponent'
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app">
  <parent-component>
    1. <child-component></child-component><br>
    2. <child-component></child-component><br>
  </parent-component><br>
  
  <parent-component>
    3. <child-component></child-component><br>
    4. <child-component></child-component><br>
  </parent-component>
</div>

By observing how the children components extract the same instance within a component while obtaining another instance within another component, we can see the flexibility in managing shared objects efficiently.

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

Sticky header in React data grid

Is there a way to implement a sticky header for a data grid in react? I have tried various methods but haven't been able to figure it out. Any suggestions would be appreciated. You can find my code sandbox example here. #react code export const Styl ...

Using a uibCollapse within a nested directive element may not function as expected

Whenever I try to click on my custom directive, the elements that are supposed to expand remain collapsed. To ensure that the click event is actually triggered, I have specified a size in the css for the .btn class. // index.html <body ng-controller=" ...

What steps are required to transform a TypeScript class with decorators into a proper Vue component?

When I inquire about the inner workings of vue-class-component, it seems that my question is often deemed too broad. Despite examining the source code, I still struggle to grasp its functionality and feel the need to simplify my understanding. Consider th ...

Error: The value of the expression has been altered after it was already checked. Initial value was 'undefined'. An exception has occurred

Although this question has been asked multiple times, I have read similar issues and still struggle to organize my code to resolve this particular exception. Within my component, there is a property that dynamically changes based on a condition: public e ...

When is it appropriate to store application data in memory?

I apologize if this is a basic question, as I am still learning about the android framework. While researching, I came across ngrx redux and flux design pattern in angular, where the entire application state is stored in a JavaScript object. It made me c ...

Clicking on an option within a div that has an ng-repeat does not update the ng-model

Why is my ngModel, myOpt2, not changing when selected while myOpt does change? Any specific reason for this? ¿Por qué mi ngModel, myOpt2, no cambia al ser seleccionado mientras que myOpt sí lo hace? ¿Hay alguna razón específica para esto? var app ...

After minifying the JS file, the $http service was not injected into the controller within a component

angular.module("datasView",[]) .component("datasView",{ templateUrl : 'dataview/datasview.template.html', controller : function control($http){ var self = this; $http.get('src/data/issues.json').then(function(res ...

Dynamically updating the scroll area in Ionic using real-time data

Hello, I am currently working on an Ionic project and have created a code pen for it. At the moment, the code pen just displays an image with two buttons for zooming in and out. However, I have encountered an issue. When I click on zoom in and scroll to ...

Can you please provide instructions on how to obtain the TypeScript definitions file for a specific version of Jquery, such as 3.2.1

As I navigate my way through TypeScript, I find myself in need of accessing type definitions for a jQuery project in Visual Studio. The project currently utilizes jquery version 3.2.1, and I'm on the lookout for TypeScript type definitions for it. Af ...

Loop through a collection of elements of a certain kind and selectively transfer only certain items to a different collection of a different kind

When working with typescript, I am faced with the challenge of dealing with two arrays: interface IFirst{ name: string; age: number } interface ISecond { nickName: string; lastName: string; } myFirstArray: IFirst[]; mySecondArray: ISe ...

Exploring the intricacies of defining Vue component props in TypeScript using Vue.extend()

Here is a simple example to illustrate my question When I directly define my props inside the component, everything works fine <script lang="ts"> import Vue, { PropType } from "vue"; export default Vue.extend({ props: { col ...

Develop a search function that can be utilized throughout the entire

At the top of my angular application, I have a single search text box. Here is an example: Users are able to enter keywords and search throughout the application. They will receive a list of links with descriptions. I have the capability to implement thi ...

Troubleshooting: Issues with Angular 2 Dependency Injection

I am facing an issue with my angular2 application that involves a simple dependency injection, but it seems to be not working correctly. Can anyone help me figure out what might be missing? Below is the error message I am encountering: EXCEPTION: Cannot ...

Connecting a string array to the navigation bar

Need Assistance with AngularJS: In my controller, I have a string array that looks like this: var app = angular.module('myApp', []); app.controller('mycontroller', function($scope) { $scope.menuitems =['Home','About&apos ...

Mastering the incorporation of Context in React with Typescript

I am currently in the process of setting up a context provider for my Next.js application using TypeScript. Although I have previously set up a context provider in React using plain JavaScript, this time I am delving into learning TypeScript. In the code ...

Comparison Between JavaScript Cookie and AngularJS $cookiesIn this comparison,

Can you explain the difference between a cookie created using JavaScript and one created using angularjs $cookies? For example, when I create a cookie using JavaScript like this: document.cookie = "username=smith";, the cookie values are retained even whe ...

Using TypeORM: Implementing a @JoinTable with three columns

Seeking assistance with TypeORM and the @JoinTable and @RelationId Decorators. Any help answering my question, providing a hint, or ideally solving my issue would be greatly appreciated. I am utilizing NestJS with TypeORM to create a private API for shari ...

When using AngularJS and PHP together, I encountered an error that stated "

My POST http request is encountering an error with the message Undefined property: stdClass::$number and Undefined property: stdClass::$message. Below are the codes I've been using: smsController.js angular .module('smsApp') .contr ...

Preserving objects/variables in non-volatile storage

SUMMARY Though I lack extensive programming experience, I am currently developing a hybrid mobile app with Cordova. The app will contain a substantial amount of static data which needs to be referenced periodically for basic operations. As the volume of o ...

Unable to render images in Angular client due to issues with accessing upload path in Express Node.js backend

I've been struggling with the issue of displaying images on the Angular client for a while now, despite going through numerous similar questions. The files are successfully uploaded to the upload folder and their details are stored in the MongoDB data ...