iJade
iJade

Reputation: 23811

Do you need to subscribe the Observable every time an API call is made?

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)
    }
}

Upvotes: 3

Views: 6074

Answers (2)

P. Moloney
P. Moloney

Reputation: 721

The way you are doing it is fine. Angular's Http Service will automatically unsubscribe (destroys the subscription) from the Observable once the call reaches it's conclusion.

However you may want to put in a peice of code that prevents multiple calls due to the user clicking 1000 times consecutively. Basic Example:

isGettingData = false;
doGET() {
    if(!this.isGettingData){
        this.isGettingData = true;
        this.service.getData().subscribe(res => {
            console.log('result is ', res);
            this.isGettingData = false;
        });
    }
}

If you are making your own Observable Variables/Services or some-such it's good practice to .unsubscribe() when the component is destroyed. Example:

myObserver: Observable<Array<any>>;
doGET() {
    this.myObserver= this.route.params.subscribe(params => {})
}

ngOnDestroy(){
    this.myObserver.unsubscribe();
}

This answer has a detailed explanation

Upvotes: 0

Chandru
Chandru

Reputation: 11192

component.ts

doGET() {
    this.service.getData()
            .subscribe(data => {
                console.log('data', data);
            });
}

service.ts

apiRoot: string = "http://httpbin.org";
getData() {
        let url = `${this.apiRoot}/get`;
        return this.http.get(url)
            .map(res => res.json());
    }

Upvotes: 1

Related Questions