Thinker
Thinker

Reputation: 5356

Angular2 consuming service that makes HTTP call in component method

I am learning Angular2 and have following doubt:

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.

My service:

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) => {

            this.data=res.json();
            this.loading=false;

            return this.data;

          });
      }

}

My component:

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(){

    }
}

My Template:

<button type="button" (click)="getData()">Make Request</button>

<div *ngIf="loading">loading...</div>
      <pre>{{data}}</pre>

How can I implement this getData() method? Is it the correct approach to consume such HTTP service?

Upvotes: 1

Views: 1053

Answers (1)

null canvas
null canvas

Reputation: 10603

Inject the service and then use it:

export class Home {

 data: Object;

 constructor(private myService:HomeService){}

 getData(){
   this.data = this.myService.fetchData();
 }
}

Upvotes: 1

Related Questions