title: Angular 4 Singleton Services
body: <p>I'm trying to create a service to share the data between two components. I injected the service into root module to make it accessible throughout the application by doing DI into the root module provider. My code looks roughly like this.</p>
  
  <p><strong>Service</strong></p>
  
  <pre><code>    @Injectable(){
      export class ForumService{
         forum: any;
  
         setForum(object){
            this.forum = object; 
         }
  
         getForum(){
            return this.forum;
         }
      }
  </code></pre>
  
  <p><strong>Root Module</strong></p>
  
  <pre><code>.......
  import { ForumService } from 'forumservice';
  .......
  
  @NgModule({
    declarations: [.....],
    imports: [.....],
    providers: [....., ForumService],
    bootstrap: [AppComponent]
  })
  export class AppModule{}
  </code></pre>
  
  <p><strong>Component One</strong></p>
  
  <pre><code>//A bunch of import statements
  
  import { ForumService } from 'forumservice'; //Without this Angular throws a compilation error
  
  @Component({
    selector: 'app-general-discussion',
    templateUrl: './general-discussion.component.html',
    styleUrls: ['./general-discussion.component.css'],
    providers: [GeneralDiscussionService]     //Not injecting ForumService again
  })
  
  export class GeneralDiscussionComponent implements OnInit{
  
    constructor(private forumService: ForumService){}
  
    ngOnInit(){
       helperFunction();
    }
  
    helperFunction(){
       //Get data from backend and set it to the ForumService
       this.forumService.forum = data;
       console.log(this.forumService.forum); //prints the data, not undefined
    }
  }
  </code></pre>
  
  <p><strong>Component Two</strong></p>
  
  <pre><code>//A bunch of import statements
  
  import { ForumService } from 'forumservice'; //Without this Angular throws a compilation error
  
  @Component({
     selector: 'app-forum',
     templateUrl: './forum.component.html',
     styleUrls: ['./forum.component.css'],
     providers: []
  })
  
  export class ForumComponent implements OnInit {
     forumData: any;
  
     constructor(private forumService: ForumService){}
  
     ngOnInit(){
        this.forumData = this.forumService.forum;  // returns undefined         
     }
  }
  </code></pre>
  
  <p>Once I navigate from Component One to Component Two I'm expecting "This is a string". However I get <code>undefined</code>. Is it because of the import statements in the component? If I remove that I see a compilation error saying that <code>ForumService</code> is not found.</p>