在我的 Angular 服务脚本(以下代码段)中,我通过 Django 从我的 MongoDB 数据库接收了一个客户资料字典:
getConsumersMongodb(): Observable<any> {
return this.httpClient.get(`${this.baseMongodbApiUrl}`);
}
回来的字典是这样的:
{
"message": "Got all consumers' info successfully!",
"consumers": {
"id": 8,
"age": "51 - 60",
"gender": "Female"
...
},
"error": "Error!"
}
我只对消费者资料感兴趣,所以我在我的 Angular 组件 TypeScript 代码中决议它,如下所示:
ngOnInit(): void {
this.dbService.getConsumersMongodb()
.subscribe(responseData => {
this.loadedConsumersDict = responseData;
this.consumersInfo = this.loadedConsumersDict["consumers"]);
console.log(this.consumersInfo);
});
}
当然,在我的开发控制台中,我得到了这个:
{id: 8, age: '51 - 60', gender: 'Female', …}
到现在为止还挺好...
现在,我需要将此 json 物件转换为可迭代物件,例如阵列,以便我可以查看其栏位并将它们显示在我的 Angular html 模板中。
所以,我修改了我的代码:
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);
});
}
但这给了我以下内容:
{id: 8}
{age: '51 - 60'}
{gender: 'Female'}
...
这不是我想要的。如何将内容放入可迭代物件中,以便我可以简单地在 html 模板代码中使用以下代码段来显示栏位?
<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>
...
我已经走了很长一段路来实作这一目标,但现在我很困惑,需要帮助。我将不胜感激任何帮助。
编辑:
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', ...}
uj5u.com热心网友回复:
consumers
在回应中是一个物件而不是一个阵列。因此,您不需要将任何内容转换为阵列,*ngFor
如果您不需要,当然也不需要使用。
只需确保这consumersInfo
是一个公共属性,然后在您的模板中写入以下内容:
<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>
...
0 评论