I am encountering an issue in my Angular application where I am unable to access a variable outside of the subscription block after calling an API in a service and subscribing to the data in a component.
.service.ts
dronedetails():Observable<object>{
let httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'Token ' + localStorage.getItem('token')
})
};
return this.http.get(environment.apiUrl +'/api/data/json', httpOptions)
After subscribing to the data in the component:
.component.ts
ngOnInit() {
this.ds.dronedetails()
.subscribe((drones)=>{
this.drones = drones;
console.log('obj',drones);
},
err=>{
console.log("Error",err)
}
);
//Attempting to use 'drones' outside of the subscription block does not work
var latlngs = this.drones.drone1.Drone.latlong;
var droneid = this.drones.drone1.Drone.Droneid;
}
If anyone has a solution for this, I would greatly appreciate the help.