Home > Mobile >  Spreading a json object into an iterable
Spreading a json object into an iterable

Time:01-05

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  *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', ...}

CodePudding user response:

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 >
    <p><i>Id:</i> {{ consumersInfo.id }}</p>
    <p><i>Gender:</i> {{ consumersInfo.gender }}</p>
    <p><i>Age Group:</i> {{ consumersInfo.age }}</p>
    ...
  •  Tags:  
  • Related