每次进行API调用时,是否需要订阅Observable?

时间:2017-09-08 05:17:03

标签: angular angular2-observables

当用户点击按钮时,doGET中的方法component.ts被调用。在doGET方法中,我正在订阅名为getData的方法,在service.ts中返回一个observable。但是,每次点击按钮或调用doGET方法时,它都不会被订阅吗?这是在Angular中进行API调用的写入方式吗? 这是我的Angular组件代码:

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

    }

}

以下是Angular服务代码:

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

你这样做的方式很好。一旦调用结束,Angular的Http服务将自动从Observable取消订阅(销毁订阅)

但是,由于用户连续点击1000次,您可能需要添加一些代码来阻止多次调用。基本示例:

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

如果您正在制作自己的Observable Variables / Services或某些 - 当组件被销毁时,.unsubscribe()是一个好习惯。例如:

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

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

This answer有详细解释