0

I am looking to make an AngularJS Typescript Service into Non-Singleton. Please suggest how can I do this. (This is not similar to other question that asks how to do it in JS) Added simple pseudo code below:

class TestService {

    private message: string;

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

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

angular.module("app").service("TestService", TestService);
k19
  • 83
  • 3
  • 10
  • 1
    All AngularJS services are singletons. – JB Nizet Jun 25 '19 at 19:36
  • Possible duplicate of [Non-Singleton Services in AngularJS](https://stackoverflow.com/questions/16626075/non-singleton-services-in-angularjs) – Doguita Jun 25 '19 at 21:04
  • @Doguita: I have already seen the mentioned link. That one explains to do this in JS. I am looking for Typescript. – k19 Jun 26 '19 at 04:29

2 Answers2

0

Instead of providing service in module level make it as provider in component level.

like below.

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

0

To have an object that is a shared instance across a component hierarchy you don't use services as they are singletons, you use requires to get an instance of a parent component and have the shared object attached to that components 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>

See how the children of the component get the same instance but the children of the other component get another instance.

Adrian Brand
  • 20,384
  • 4
  • 39
  • 60