0

I was looking into "how to use Constants on Angular2" and found this post with this answer where one have to create a class with an OpaqueToken, import it on app.module and use it as a provider in the @NgModule. In the Page Class or service import it and inject it with @Injectable().

Then I searched on how to create a "factory like in AngularJS" and find out this post about sharing data between components in Ionic2, in it you create a simple class without an OpaqueToken and import it in app.components, register it as provider on @Component and in the App constructor. Finally import it on the page class and inject it (no need to use @Inject())

Is there a difference between this two? at first glance seams like those both do the exact same thing and I find the second way easier.

Edit

User estus pointed out in a comment, the first one with the OpaqueToken will inject a class and the second example inject a class instance. Does this means that with the first example every page will have their own instance of that class ? so 10 pages = 10 instances ? is it not counterproductive (or inefficient) for share static data/constants between them?

Community
  • 1
  • 1
distante
  • 6,438
  • 6
  • 48
  • 90
  • `OpaqueToken` is used in `useValue` providers exclusively. The first example injects a class. The second injects class instance. Considering that you have experience with A1, the things you're asking is already available in the question you've quoted, here http://stackoverflow.com/a/34987036/3731501 . – Estus Flask Feb 08 '17 at 17:44
  • Yes but, that question was corrected by the question I posted with the "official correct way". Also the link for that documentation does not exist anymore. – distante Feb 09 '17 at 05:52
  • the number of instances depends on *where* you set as provider..If you set in **ngModule** it is a singleton and if you try to set in **component** it creates an instance for the component. – Suraj Rao Feb 09 '17 at 06:16
  • Again, OpaqueToken helps to inject a class, to create an instance manually with `new`, constructor args may be service deps or something else. The same thing as `app.value('Class', Class)` in A1. This is for the cases when you need 10 instances. It is up to you if it is efficient or not. If you misuse this, then yes, it is counterproductive. – Estus Flask Feb 09 '17 at 08:39

0 Answers0