簡體   English   中英

捕獲從服務到組件的響應?

[英]Catch response from service to component?

我是角度/離子的新手。 我正在嘗試從我的API調用中獲取響應。

在我的服務中,我具有以下功能:

setClockIn() {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': 'bearer'
      })
    };
    this.http.get('http://127.0.0.1:8000/api/v1/clock/in', httpOptions)
    .subscribe(data => {
    console.log(data['data']);
    });
  }

在我的組件中,我具有以下功能

ClockIn() {
    this.clockService.setClockIn();
    this.presentAlert(data);
  }

來自console.log(data['data']);的響應 是我從API發送的消息:

“時鍾已更新”

我如何才能在同一ClockIn函數中獲取此數據,以便將其作為參數發送給this.presentAlert(data); ;。

我必須使用.subscribe().pipe().map()嗎?

angular的HttpClient的HTTP GET請求返回一個observable ,因此基本上,您應該從setClockIn()方法返回observable,並在您組件的ClockIn()方法中進行訂閱

setClockIn() {
    const httpOptions = {
      headers: new HttpHeaders({
        'Content-Type':  'application/json',
        'Authorization': 'bearer'
      })
    };

    return this.http.get('http://127.0.0.1:8000/api/v1/clock/in', httpOptions);
}


ClockIn() {
    this.clockService.setClockIn().subscribe(data => {
        console.log(data['data']);
        this.presentAlert(data);
    });  
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM