I am working on a function that retrieves a JSON file from a specific URL. The issue I am facing is that I am trying to access a random object from this data within the file, stored in this.data. However, when I attempt to console.log(this.data) outside of the .subscribe function, it returns undefined. What steps can I take to utilize this value throughout the rest of the function and pass it to another function?
Provided below is my code snippet:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
/*
Generated class for the AdsProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
@Injectable()
export class AdsProvider {
adsUrl: string;
constructor(public http: HttpClient) {
console.log('Hello AdsProvider Provider');
}
getAds() {
this.adsUrl = 'an url';
console.log(this.adsUrl);
console.log('I can get ads');
// Requesting the file from the server
let data: Observable<any> = this.http.get(this.adsUrl);
data.subscribe(result => {
this.data = result;
// JSON file containing advertisements retrieved successfully
});
console.log(this.data); // This output shows as undefined
}
}