I have a method doGET
in component.ts
being called when user clicks the button. Inside the doGET
method I'm subscribing to the method called getData
returning an observable in service.ts
. But doesn't it gets subscribed each time I'm clicking the button or calling the doGET
method? Is this the write way to make API calls in Angular ?
Here is my Angular component code:
import { Component } from '@angular/core';
import { AppService } from './app.service'
import { Http, Response, RequestOptions, Headers } from '@angular/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [AppService]
})
export class AppComponent {
title = 'app works!';
constructor(private service: AppService) {
}
doGET() {
this.service.getData().subscribe(res => {
console.log('result is ', res);
})
}
}
Here is the Angular service code :
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from "@angular/http";
@Injectable()
export class AppService {
apiRoot: string = "http://httpbin.org";
constructor(private http: Http) { }
getData(){
let url = `${this.apiRoot}/get`;
return this.http.get(url)
}
}