2017-09-08 205 views
1

我有一個方法doGETcomponent.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) 
    } 
} 

回答

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

如果您正在製作自己的觀測變量/服務或一些,因此它是很好的做法,以.unsubscribe()當組件被銷燬。例如:

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

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

This answer有詳細的解釋

相關問題