1

In my Angular service script (following snippet) I receive a dictionary of customer data from my MongoDB database via Django:

getConsumersMongodb(): Observable<any> {
    return this.httpClient.get(`${this.baseMongodbApiUrl}`);
}

The dictionary that comes back is like this:

{
    "message": "Got all consumers' info successfully!",
    
    "consumers": {
        "id": 8, 
        "age": "51 - 60", 
        "gender": "Female"
        ...
    },
    
    "error": "Error!"
}

I am only interested in consumers data, so I parse it out in my Angular component TypeScript code like this:

ngOnInit(): void {

    this.dbService.getConsumersMongodb()
      .subscribe(responseData => {
        this.loadedConsumersDict = responseData;
        this.consumersInfo = this.loadedConsumersDict["consumers"]);
        console.log(this.consumersInfo);
      });
}

Of course, in my dev console, I get this:

{id: 8, age: '51 - 60', gender: 'Female', …}

So far, so good...

Now, I need to convert this json object into an iterable, such as an array, so that I can go through its fields and display them in my Angular html template.

So, I modified my code to 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);
      });
}

But this gives me the following:

{id: 8}
{age: '51 - 60'}
{gender: 'Female'}
...

This is not what I want. How do I place the content into an iterable, so that I can simply use my following snippet in my html template code to display the fields?

<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 have come a long way to achieve this much, but now I am confused and need help. I would appreciate any help.

EDIT:

This is what I have written in 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)

The print statement prints this:

[OrderedDict([('id', 8), ('age', '51 - 60'), ('gender', 'Female'), ...])]

Because it always contains one item in this Python list, I do:

consumers_serializer.data[0]

to ensure that the response I get is this:

{'id': 8, 'age': '51 - 60', 'gender': 'Female', ...}
Muhy
  • 630
  • 1
  • 6
  • 12
  • There is [no such thing as a JSON-'object'](https://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – KooiInc Jan 03 '22 at 15:50
  • If the JSON coming from the database is a dictionary you can't convert it to an array and it wouldn't make sense since there are no duplicate keys in a dictionary. Do you have multiple id's coming from the database? Are you sure your "dictionary" isn't actually an array of dictionaries in which case you don't need to do any more manipulations. – Whitewolf3131 Jan 03 '22 at 15:51
  • 2
    The data is already in the format you want... Why convert it to an array and use it in a ngFor? – madflow Jan 03 '22 at 15:54
  • 1
    You has not an array of object just an unique object. You can use [KeyValue pipe](https://angular.io/api/common/KeyValuePipe) to "split" and show the properties and values, but I don't know if this is what are you looking for – Eliseo Jan 03 '22 at 16:03
  • Are you sure that `consumers` is an object and if so how does it carry multiple consumers? – Redu Jan 03 '22 at 16:27
  • https://stackoverflow.com/questions/52793944/angular-keyvalue-pipe-sort-properties-iterate-in-order – Danail Videv Jan 03 '22 at 16:33
  • @Whitewolf3131 I have added an edit to answer your question about the list and dictionary. – Muhy Jan 04 '22 at 12:10

1 Answers1

1

consumers in the response is an object and not an array. Therefore, you don't need to convert anything into an array, and surely no need to use *ngFor if you don't have to.

Just make sure that consumersInfo is a public property, and then in your template write the following:

<li class="list-group-item">
    <p><i>Id:</i> {{ consumersInfo.id }}</p>
    <p><i>Gender:</i> {{ consumersInfo.gender }}</p>
    <p><i>Age Group:</i> {{ consumersInfo.age }}</p>
    ...
Lorraine R.
  • 1,545
  • 1
  • 14
  • 39