title: Inject service as singleton for all components in Angular 4
body: <p>Sorry if duplicate, I've read related posts, but didn't find (or didn't understand) an answer.</p>
  
  <p>I have a service that is used by many components and I want it to be a singleton for all components (throughout all app).
  This service must send a request and get data once and then share this data among other components.</p>
  
  <p>Here's some code as example:</p>
  
  <p><strong>app.module.shared.ts</strong> </p>
  
  <pre><code>import { MyService } from '../services/myservice';
  
  @NgModule({
      declarations: [
           //...
      ],
      imports: [
          //...
      ],
      providers: [
          MyService
      ]
  })
  </code></pre>
  
  <p><strong>myservice.ts</strong></p>
  
  <pre><code>@Injectable()
  export class MyService {
      shareData: string;
  
      constructor(private http: Http, @Inject('BASE_URL') private baseUrl: string) { }
  
      getSharedData(): Promise&lt;string&gt; {
          return new Promise&lt;string&gt;(resolve =&gt; {
              if (!this.shareData) {
                  this.http.get(this.baseUrl + "api/sharedDara").subscribe(result =&gt; {
                      this.shareData = result.json() as string;                    
                      resolve(this.shareData);
                  }, error =&gt;  console.log(error));
              } else {
                  resolve(this.shareData);
              }
          });
      }
  }
  </code></pre>
  
  <p><strong>example.component.ts</strong> (the example of usage)</p>
  
  <pre><code>import { MyService } from '../services/myservice';
  
  @Component({
      selector: 'example',
      templateUrl: './example.component.html',
      styleUrls: ['./example.component.css']
  })
  export class ExampleComponent implements OnInit {
  
      sharedData: string;
  
      public constructor(private myService: MyService,
          @Inject('BASE_URL') private baseUrl: string) { }
  
      ngOnInit() {
          this.myService.getSharedData().then(result =&gt; this.sharedData= result);
      }
  }
  </code></pre>
  
  <p><a href="https://angular.io/guide/dependency-injection#singleton-services" rel="noreferrer">Documentation</a> says:</p>
  
  <blockquote>
    <p>Dependencies are singletons within the scope of an injector.</p>
  </blockquote>
  
  <p>As I understand that for each component its own instance of a service is created. Is it right? And how to make a single instance of a service for all components?</p>
  
  <p>Thanks in advance.</p>