简体   繁体   中英

Catch response from service to component?

I'm new on angular/ionic. I'm trying to fetch a response from my API call.

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']); is my message from the 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); ?

I must use .subscribe() or .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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM