Ughh...
I'm brand new to Angular (about 2 weeks), and have been looking at RxJS examples on stackoverflow for days, and just cannot figure this out and am under time pressure at work. I know this question has been asked before, and I tried many different examples, but am still stumped. I have a small Angular application that makes a call to a RESTful API. I would like to be able to extract the value "F86292" of the property "flagName" from the API response below:
{
"headers": {},
"body": [
{
"flagId": 2,
"flagParentId": 0,
"flagTypeId": 1,
"flagName": "F86292",
"flagDesc": null,
"flagToggleState": 0
}
],
"statusCode": "OK",
"statusCodeValue": 200
}
I can successfully make a call to the API service and retrieve the JSON above using the following code snippets below (omitted code denoted by ellipses):
interface ServerData {
headers: Object;
body: Array<any>;
statusCodeValue: number;
statusCode: string;
}
. . .
flagData$: Observable<ServerData>;
. . .
this.flagData$ = this.http.get<ServerData>(this.url, options).pipe(
map(
response =>
({
headers: response.headers,
body: response.body,
statusCodeValue: response.statusCodeValue,
statusCode: response.statusCode
} as ServerData)
)
);
I can then display the values statusCodeValue
and statusCode
in my template html because they are first-level properties of the nested response object. However, I am unable to retrieve "flagName" and other properties from the response body.
<table *ngIf="flagData$ | async as flag">
<tr>
<td class="heading">
Flag Id
</td>
<td>
{{ flag.statusCode }}
</td>
<tr>
I have tried several examples out there that use pipe, map, etc. and just cannot make it work.
Any help you can offer would be greatly appreciated. Thank you so much for your help!
Note: Per Zircon's recommendations below, I changed ServerData above
FROM body: Object;
TO body: Array<any>;
This combined with his solution worked! Thank you Zircon!! :-)
flagData$
is an Observable<ServerData>
. When you use the async
pipe on it, the result is the data from the Observable, in this case a ServerData
object.
This is why you can easily display the statusCode
via {{ flag.statusCode }}
in your template. But there are no nested Observable
s in this object. Rather, the data you need is "nested" within inner objects of flag
.
If you want to specifically show the value "F86292" from your response, the path to use in your template would be {{ flag.body[0].flagName }}
because flag.body
is an array.
If you wanted to display each flagName
that could appear in that array, you could use *ngFor
. Here is an example of showing some info of each element of body
per row:
<tr *ngFor="let bodyEl of flag.body">
<td>{{ bodyEl.flagId }}</td>
<td>{{ bodyEl.flagName }}</td>
</tr>
The above code could be read as "for each element of flag.body
, create a table row that shows its flag ID and name."