sadjapa
sadjapa

Reputation: 15

How to receive a value from a service in IONIC 4?

I am developing an App in IONIC that receives values ​​from the database through an API in Laravel, I get the value in the service but I can not pass this value to another page where I am calling the service

My function in service looks like this:

get(){
const headers = new HttpHeaders({
      'Authorization': this.token["token_type"]+" "+this.token["access_token"]
    });
return new Promise ((resolve)=>{
     this.http.get(this.env.API_URL+'auth/get',{ headers: headers }).subscribe((result:any)=>{
      this.date = result; //thats ok
      console.log(this.date);
      return this.date;
    },
    (error)=>{
      console.log(error);
    });
   });
}

The function I call Service is this:

showdata(){
this.authService.getReuniao().then((response)=>
    {
      this.data_r = response;
    })
    .catch((response)=>{
      this.data_r = JSON.stringify(response);
    });
console.log('didn't enter...');
}

But it doesn't even come in then and it falls straight out. Am I getting it wrong ???

Upvotes: 0

Views: 189

Answers (1)

jcmendes98
jcmendes98

Reputation: 148

Try this way.

getReuniao(): Observable<any> {

return this.http.get<any>( this.env.API_URL+'auth/getreuniao')
.pipe(
retry(1),
catchError(this.handleError)
)           

}; Work with errors in the the same service.ts:

handleError(error) {
let errorMessage = '';
if(error.error instanceof ErrorEvent) {
// Get client-side error
errorMessage = error.error.message;
} else {
// Get server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
window.alert(errorMessage);
return throwError(errorMessage);
}

Now let's call the api service. Don't forget to add the service to providers and call it on the construct.

this.api.getReuniao().subscribe(data=>{ console.log("data:" + data)}, error=>{ console.log("error: " + error});

Use Subscribe instead with observable.

Upvotes: 1

Related Questions