简体   繁体   English

捕获从服务到组件的响应?

[英]Catch response from service to component?

I'm new on angular/ionic. 我是角度/离子的新手。 I'm trying to fetch a response from my API call. 我正在尝试从我的API调用中获取响应。

Inside my service i have the following function: 在我的服务中,我具有以下功能:

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

And in my component i have the following function 在我的组件中,我具有以下功能

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

The response from console.log(data['data']); 来自console.log(data['data']);的响应 is my message from the API: 是我从API发送的消息:

"Clock updated" “时钟已更新”

Altough how can i fetch this data inside the same ClockIn function in order to send it as parameter to this.presentAlert(data); 我如何才能在同一ClockIn函数中获取此数据,以便将其作为参数发送给this.presentAlert(data); ;。 ?

I must use .subscribe() or .pipe().map() ? 我必须使用.subscribe().pipe().map()吗?

The HTTP GET request of angular's HttpClient returns an observable , so basically you should return the observable from the setClockIn() method and subscribe to it in the ClockIn() method of your component 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