Home > Back-end >  How to get the components from a json file from an observable in angular?
How to get the components from a json file from an observable in angular?

Time:07-07

Consider the code:

res: any;

getData(url: any) {
    this.res = this.http.get(url);
}

ngOnInit(): void {
     getData("url.com/file.json");
     console.log(this.res)
}

In the console I get

Observable {source: Observable, operator: ƒ}

How do I get the contents of the json file instead of an observable?

CodePudding user response:

First, the way you define the property and use the httpClient verbs in unconventional. If you want to assign the Http verb (i.e GET) to a property this property will hold an Observable, because HttpClient verbs return Observables in Angular and they are powered by RxJS under the hood.

Second, with this being said, if you want to get into the JSON part you need to subscribe to the Observable i.e listen to the values that will be broadcasted by the Observer.

You have two ways to do that;

1 - As per Andrew description by assinging the JSON to the property within the subscription.

2- You keep the property assigned an Observable and use async pipe in your template.

Now, why you are getting undefined ? because during initialization of the component your asynchronous data has not been assinged yet to your property. Here, you have multiple options, including using a different lifecycle hook such as ngAfterViewInit or use a guard condition to check

if(res) { //stuff}

In all cases, you need a small refactoring for the unconventional way of handling Http calls as in your code snippets above.

CodePudding user response:

You need to subscribe to the observable.

getData(url: any) {
    this.http.get(url).subscribe(result => { this.res = result; });
}
  • Related