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
})
}
There are two ways to use app.service.ts
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) => {})
}
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) => {})
}