title: Angular2 consuming service that makes HTTP call in component method
body: <p>I am learning Angular2 and have following doubt:</p>
  
  <p>I have written a service that makes an HTTP request and fetches data. In my component I want to have a method that consumes this service and on HTML template of that component I have a button which onClick calls this method.</p>
  
  <p><strong>My service:</strong></p>
  
  <pre><code>import {Injectable} from '@angular/core';
  import { Http, Response } from '@angular/http';
  import { Observable }     from 'rxjs/Observable';
  
  @Injectable()
  export class HomeService{
  
      data: Object;
      loading: boolean;
  
      constructor(private http: Http){}
  
      public myUrl = 'http://jsonplaceholder.typicode.com/users';
  
      fetchData(): any {
  
          this.loading = true;
          this.http.request(this.myUrl)
            .subscribe(
              (res: Response) =&gt; {
  
              this.data=res.json();
              this.loading=false;
  
              return this.data;
  
            });
        }
  
  }
  </code></pre>
  
  <p><strong>My component:</strong></p>
  
  <pre><code>import {Component} from '@angular/core';
  import { ROUTER_DIRECTIVES } from '@angular/router';
  
  import {HomeService} from './home.component.service';
  
  
  
  @Component({
  
      selector:'home',
      templateUrl:'./app/Home/home.component.html',
      providers:[HomeService],
      directives: [ROUTER_DIRECTIVES]
  
  })
  export class Home {
  
      data: Object;
  
      constructor(){}
  
      getData(){
  
      }
  }
  </code></pre>
  
  <p><strong>My Template:</strong></p>
  
  <pre><code>&lt;button type="button" (click)="getData()"&gt;Make Request&lt;/button&gt;
  
  &lt;div *ngIf="loading"&gt;loading...&lt;/div&gt;
        &lt;pre&gt;{{data}}&lt;/pre&gt;
  </code></pre>
  
  <p>How can I implement this getData() method? Is it the correct approach to consume such HTTP service? </p>