javascriptangulartypescriptapi

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

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) => {})
    }