我有一個方法doGET
在component.ts
當用戶點擊按鈕時被調用。在doGET
方法中,我訂閱了名爲getData
的方法,返回service.ts
中的可觀察值。但是,每次點擊按鈕或調用doGET
方法都不會訂閱它嗎?這是在Angular中進行API調用的寫入方式嗎? 這裏是我的角度分量代碼:您是否需要在每次調用API時訂閱Observable?
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);
})
}
}
這裏是角服務代碼:
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)
}
}