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

Modifying the appearance of a Component within a NavLink

I'm currently working on a navbar using NavLink from React-Router-Dom. It's fine to use the 'isActive' prop to style the active Link, but I'm stuck on how to style the subelements inside it. For more specific details, please take a ...

The onload function on the iframe is triggering twice in Internet Explorer 11

I am encountering a strange issue with an iframe in HTML that has an onload function. When using IE11, the onload function is being triggered twice, whereas it works fine in Chrome. Here is the HTML code: <iframe src="someurl" onload="someFunction( ...

What is the best way to showcase the content from multiple uploaded files?

Below is an example demonstrating how to display the contents of a single uploaded file. .js $scope.uploadFilename = function (files) { if (!files[0]) { return; } var reader = new FileReader(); reader ...

Error: Unable to locate the property 'indexOf' within an undefined value

I encountered an error when running my controller file. **TypeError: Cannot read property 'indexOf' of undefined** if (attribute.attributeId == 'created_on_attr' || attribute.attributeId == 'modified_on_attr' || attr ...

Having trouble with the submit button when using AngularJS and ModelForm?

My goal was to design a page that would showcase the contents of the database in a table format, with an added functionality of allowing users to input a new entry using a form. Initially, everything was functioning as intended with a "New" button triggeri ...

a guide to incorporating Google Maps into your website using latitude and longitude coordinates

After retrieving a list of latitudes and longitudes from my API for an AngularJS application, I want to display a Google map indicating the positions of these coordinates. I attempted using an iFrame but it only displayed a blank page since the latitudes ...

The functionality of "subscribe()" is outdated if utilized with "of(false)"

My editor is flagging the usage of of as deprecated. How can I resolve this issue and get it working with of? public save(): Observable<ISaveResult> | Observable<boolean> { if (this.item) { return this.databaseService.save(this.user ...

Angular 5 experiencing issues with external navigation functionality

Currently, I am attempting to navigate outside of my application. I have experimented with using window.location.href, window.location.replace, among others. However, when I do so, it only appends the href to my domain "localhost:4200/". Is it possible th ...

Save updated tags only when the form is submitted in ngTagsInput

Can the sending of a new tag to the server be disabled after adding it to the input and saving it later by clicking a submit button? This is my Controller: vm.tags = []; $scope.loadTags = function (query) { return $http.get('api/tags?query=' ...

Clearing the filename in a file type input field using React

When using this input field, only video files are accepted. If any other types of files are uploaded by enabling the "all files" option, an alert will be displayed. While this functionality is working correctly, a problem arises if a non-video file is adde ...

Error encountered during sequelize synchronization: SQL syntax issue detected near the specified number

Four Sequelize Models were created using sequelize.define();. Each model is similar but with different table names. To avoid manual creation of tables in MySQL cli, the decision was made to use sequelize.sync() in the main index.js file to allow Sequelize ...

Express server experiencing issues with generating Swagger documentation

I've been working on an Express API and decided to implement documentation using Swagger and JSDoc. However, the documentation is not working as expected. Here's how I've set it up: docs.ts: import swaggerJSDoc, { Options } from "swagg ...

Encounter a Typescript error when dealing with "app.ws" while using express-ws

I have a small project in mind where I want to create a BabyCam that can be accessed from any web browser using a Raspberry Pi Zero. My plan is to set up a web socket using express-is to stream video to multiple clients. I'm utilizing the raspivid-str ...

Browsers seem to only respond to the FileReader onload event on the second try

Currently I am working on implementing in-browser image processing using HTML5 and encountering a strange issue specifically in Chrome. The problem lies with the onload event handler for the File API FileReader class, as the file is only processed correctl ...

Organize data by month using angularjs

I'm working on an HTML page that displays a categorized list of data for each month. Here's a snippet of how the page looks: July, 2014: Monday 7th Data 7 Data 6 Friday 4th Data 5 Data 4 May, 2014: Sunday 15th Data 3 Thursday 8th Data ...

Exploring the ways to retrieve the returned Dynamic scope in AngularJS

There's a specific need I have - I require a single AngularJS function that can dynamically return the scope variable based on an input parameter. When it comes to controller functions, I've come across examples of how to achieve this dynamic sco ...

At what point do we employ providers within Angular 2?

In the Angular 2 documentation, they provide examples that also use HTTP for communication. import { HTTP_PROVIDERS } from '@angular/http'; import { HeroService } from './hero.service'; @Component({ selector: 'my-toh&ap ...

RTK Query - executing a query upon mounting with lazy loading enabled

Should rerendering be triggered by sending a request on mount? Or is the use of useEffect necessary? (Is lazy mode different from regular queries?) export const Catalog: React.FC<CatalogProps> = ({ object, category }) => { const [getCatalogPro ...

Tips for effectively packaging the React 17 library alongside the latest JSX transformation feature as an ES Module

I am currently in the process of creating a basic library consisting of React components that I intend to publish as an ES Module package for NPM. With the utilization of React 17, I have incorporated the new JSX transform into my code. To generate the ES ...

Navigating the proper utilization of exports and subpaths in package.json with TypeScript

As a newbie in creating npm packages using TypeScript, I've encountered some issues that I believe stem from misinterpreting the documentation. Currently, I am working with Node 16.16.0 and npm 8.13.2. Here is the structure of my project: src/ ├─ ...