i’m learning Angular and i have small problem with display responded data after HTTP get.
I’, requesting:
private url = 'http://localhost:8070/app';
private descriptors = '/myapp/test';
constructor(private http: HttpClient) {
}
getDescriptors(): Observable<Descriptor[]> {
let params = new HttpParams().set('methodType', 'firstVar').set('provider', 'secondVar');
return this.http
.get<Descriptor[]>(this.url + this.descriptors, {params})
.pipe(tap(console.log));
}
Additionally, i have component
response: any;
getDescriptors(){
this.response = this.http.getDescriptors().subscribe();
}
Descriptor[] is only:
export interface Descriptor {
values: string;
}
And the HTML file:
{{ response | json}}
and i have response:
{ "closed": true, "_parentage": null, "_finalizers": null, "isStopped": true, "destination": null }
and error in console:
ERROR TypeError: Converting circular structure to JSON
--> starting at object with constructor 'SafeSubscriber'
| property '_finalizers' -> object with constructor 'Array'
| index 0 -> object with constructor 'OperatorSubscriber'
--- property '_parentage' closes the circle
at JSON.stringify (<anonymous>)
at JsonPipe.transform (common.mjs:4540:21)
at Module.ɵɵpipeBind1 (core.mjs:20893:22)
at AppComponent_Template (app.component.html:3:1)
at executeTemplate (core.mjs:10534:9)
at refreshView (core.mjs:10419:13)
at refreshComponent (core.mjs:11480:13)
at refreshChildComponents (core.mjs:10210:9)
at refreshView (core.mjs:10469:13)
at detectChangesInternal (core.mjs:11624:9)
In console I see that I’ve received correct JSON:
{values: {…}}
values : inputParameters : (2) [{…}, {…}]
location : "Country"
methodType : "Method"
....
....
and so on...
Could you please help me how to get the body answer from request? I see that it is not so obvious like in general JS.
Thanks
>Solution :
To get the response data, you need to provide a callback function to the subscribe() method. This function will be called with the response data when it’s available.
See below an example of how you could the body response.
getDescriptors() {
this.http.getDescriptors().subscribe(
(data) => {
this.response = data;
console.log(this.response); // just to make sure it works
},
(error) => {
console.error(error);
}
);
}
In this code, the getDescriptors() method now calls subscribe() with two callback functions: one for handling the response data ((data) => { … }) and one for handling errors ((error) => { … }). When the response data is received, the data argument contains the parsed JSON object. You can assign it to the response property to display it in the template.