title: Angular 2 - Singleton Services?
body: <p>In Angular 1 I frequently used <strong>factories</strong> for services to store shared state accessible by many components. It looks like in Angular 2 all services that are injected as @Injectable() are created each time, thus losing the shared state.</p>
  
  <p>I 'register' the service at the root module's <code>providers</code> meta key, but still I get a transient instance.</p>
  
  <p>What I have:</p>
  
  <pre><code>Injectable()
  export class ArtistService {
     constructor(private http:Http) {
       // firing on each injection
       console.log("ArtistService ctor");
     }
  
  }
  </code></pre>
  
  <p>to call it in a component then:</p>
  
  <pre><code>@Component({
      selector: 'artist-display',
      templateUrl: './artistDisplay.html',
  })
  export class ArtistDisplay  {
      constructor(private artistService: ArtistService) {
             // instance is fine but transient
      }
  }
  </code></pre>
  
  <p>And the definition of the module:</p>
  
  <pre><code>@NgModule({
    declarations: [...],
    imports: [BrowserModule, FormsModule, HttpModule,
      RouterModule.forRoot(rootRouterConfig)],
    providers   : [
        ArtistService,
  
        // make sure you use this for Hash Urls rather than HTML 5 routing
        { provide: LocationStrategy, useClass: HashLocationStrategy },
    ],
    bootstrap: [AppComponent]
  })
  </code></pre>
  
  <p>I suspect there is maybe some other way to 'register' the <code>ArtistService</code> so it stays loaded as a static instance? Is that possible via DI or is it necessary to create a static instance method manually?</p>
  
  <p><strong>Update:</strong><br>
  Turns out that the above code <strong>does work</strong>. I was looking in the wrong place along with a logic error that caused data not to cache correctly. </p>
  
  <p>The above code works and assigning the service in the <code>providers</code> section of the <strong>top level AppModule</strong> is the key to making the parent reference stay loaded for the duration of the AppComponent. which effectively stays loaded for the lifetime of the app providing the <strong>Singleton</strong> instance. </p>
  
  <p>To get a <strong>transient</strong> instance you can declare the <code>providers</code> meta tag and the service name <strong>on the actual component</strong> which will then create the service whenever the component is loaded/re-loaded.</p>