In my Angular service script, I am fetching customer data from a MongoDB database using Django:
getConsumersMongodb(): Observable<any> {
return this.httpClient.get(`${this.baseMongodbApiUrl}`);
}
The returned dictionary looks like this:
{
"message": "Got all consumers' info successfully!",
"consumers": {
"id": 8,
"age": "51 - 60",
"gender": "Female"
...
},
"error": "Error!"
}
I only need the consumer data, so in my Angular component TypeScript code, I parse it out like this:
ngOnInit(): void {
this.dbService.getConsumersMongodb()
.subscribe(responseData => {
this.loadedConsumersDict = responseData;
this.consumersInfo = this.loadedConsumersDict["consumers"];
console.log(this.consumersInfo);
});
}
After retrieving the data, I want to convert the JSON object into an iterable array for display in my Angular HTML template. I updated my code to achieve this:
ngOnInit(): void {
this.dbService.getConsumersMongodb()
.subscribe(responseData => {
this.loadedConsumersDict = responseData;
this.consumersInfo = this.loadedConsumersDict["consumers"];
let temp = this.loadedConsumersDict["consumers"];
this.loadedConsumersArray = Object.keys(temp).map(function (key) {
return { [key]: temp[key] };
});
console.log(this.loadedConsumersArray);
});
}
However, the current output is not as expected. How do I properly format the data into an iterable array for easy display in my template?
<li class="list-group-item" *ngFor="let consumer of loadedConsumersArray">
<p><i>Id:</i> {{ consumer.id }}</p>
<p><i>Gender:</i> {{ consumer.gender }}</p>
<p><i>Age Group:</i> {{ consumer.age }}</p>
...
I've made progress with displaying the data but now seeking assistance to properly structure it. Any guidance would be appreciated.
EDIT:
This is the relevant snippet from my Django's views.py
script:
@csrf_exempt
@api_view(['GET', 'POST', 'DELETE'])
def handle_consumer(request):
if request.method == 'GET':
try:
consumers = ConsumerModel.objects.all()
consumers_serializer = ConsumerModelSerializer(consumers, many=True)
# Fetch consumer data from MongoDB.
print(consumers_serializer.data)
# end fetch region
response = {
'message': "Got all consumers' info successfully!",
'consumers': consumers_serializer.data[0],
'error': "Error in GET try"
}
return JsonResponse(response, status=status.HTTP_200_OK)
except:
error = {
'message': "Fail! Cannot get all consumers!",
'consumers': "[]",
'error': "Error in GET except"
}
return JsonResponse(error, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
And when printing the data, I ensure that it's structured correctly:
[OrderedDict([('id', 8), ('age', '51 - 60'), ('gender', 'Female'), ...])]
By accessing the first item in the list, I get the desired response:
{'id': 8, 'age': '51 - 60', 'gender': 'Female', ...}