0

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() ?

Koushik Ravulapelli
  • 1,140
  • 11
  • 30
CitizenG1
  • 185
  • 8
  • 21
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Igor May 01 '19 at 20:18

1 Answers1

1

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);
    });  
}
Muizz Mahdy
  • 798
  • 2
  • 8
  • 24