Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use API in app.service.ts in Angular an use its data in the app components

I am writing a servise.ts in which used API .But when I want to use its data in a component it’s undefined.
I used all dependencies

app.component.ts:
constructor(private DATA: DataInfoService){}
this.DATA.ApiService()
this.Informations = this.DATA.Informations;

And

DataInfoService.ts:

@Injectable({
  providedIn: 'root'
})...
constructor(private http: HttpClient) { }
public ApiService(info: INFO): any {
    var headers = info.headers;
    this.http.post<any>(APIAddress, info.postData, { headers }).subscribe(data => { 
    this.Informations = data
 })
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There are two ways to use app.service.ts

  1. Using as observable

api.service.ts

@Injectable({
  providedIn: 'root'
})...
constructor(private http: HttpClient) { }
public ApiService(info: INFO): any {
    var headers = info.headers;
    return this.http.post<any>(APIAddress, info.postData, { headers })
}


app.component.ts:

constructor(private DATA: DataInfoService){}

ngOnInit(){
  this.DATA.ApiService().subscribe((response) => {
     console.log("Response:", response)
  }, (error) => {})
}
  1. Using as promise

api.service.ts

@Injectable({
  providedIn: 'root'
})...
constructor(private http: HttpClient) { }
public ApiService(info: INFO): any {
    var headers = info.headers;
    return new Promise((resolve, reject) => {
       this.http.post<any>(APIAddress, info.postData, { headers 
       }).subscribe((response) => {
          resolve(response)
       }, (error) => {
          reject(error);
       })
    })
}


app.component.ts:

constructor(private DATA: DataInfoService){}

ngOnInit(){
  this.DATA.ApiService().then((response) => {
     console.log("Response:", response)
  }).catch((error) => {})
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading