我正在设置一个 pyramid 后端和一个棱角前端应用程序.
HTTP GET请求从Angular发送到Pyramid.
在Pyramid中,一个类(List())用于转换数据(使用__json__函数).
当Pyramid使用json渲染器响应GET请求时,Angular端接收的数据并不像预期的那样. id看起来像是Array类型,它包含id的值.
下面是使用__json__函数定义类List的代码:
class List():
id = None
def __init__(self, Id, Name, Image):
self.id = Id,
self.name = Name
def __json__(self, request):
return {
'Id':self.id,
'Name':self.name
}
使用json渲染器进行GET请求的视图:
@view_config(route_name='lijsten', renderer='json', request_method='GET')
def lijsten_view(request):
request.matchdict['lijstID'] == 'techniek':
technieken = {
"01" : "Berliner wand" ,
"02" : "Secanspalen wand",
"03" : "Cutter Soil Mix wand",
"10" : "Avegaarpaal",
"11" : "Verbuisde Boorpaal",
"12" : "Grondverdingende Schroefpaal",
"13" : "Funderingsput",
"14" : "Micropaal"
}
jsonlist = []
for key, value in technieken.items():
tech = List(str(key), str(value), '')
jsonlist.append(tech)
return jsonlist
在Angular端,get. Technieken()用于发送GET请求:
getTechnieken(): Observable<Techniek[]> {
this.messageService.add('DataService: technieken aangevragen')
const url = `${this.restUrl}/lijsten/techniek`;
return this.http
.get<Techniek[]>(url)
.pipe(
//tap(_ => this.log('fetched lijsten on: ' + url )),
catchError(this.handleError<Techniek[]>('getTechnieken', []))
);
}
当将返回的Array打印到控制台时,我得到以下内容:
Array(8) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
0: Object { Id: (1) […], Name: "Berliner wand" }
Id: Array [ "01" ]
0: "01"
length: 1
<prototype>: Array []
Name: "Berliner wand"
<prototype>: Object { … }
1: Object { Id: (1) […], Name: "Secanspalen wand" }
2: Object { Id: (1) […], Name: "Cutter Soil Mix wand" }
3: Object { Id: (1) […], Name: "Avegaarpaal" }
4: Object { Id: (1) […], Name: "Verbuisde Boorpaal" }
5: Object { Id: (1) […], Name: "Grondverdingende Schroefpaal" }
6: Object { Id: (1) […], Name: "Funderingsput" }
7: Object { Id: (1) […], Name: "Micropaal" }
我展开了数组中的第一个对象,其中Id被标识为数组,它应该是一个字符串:Id:"01"...
根据Pyramid文档,预期的输出如下所示:
from pyramid.view import view_config
class MyObject(object):
def __init__(self, x):
self.x = x
def __json__(self, request):
return {'x':self.x}
@view_config(renderer='json')
def objects(request):
return [MyObject(1), MyObject(2)]
# the JSON value returned by ``objects`` will be:
# [{"x": 1}, {"x": 2}]
我不清楚我做错了什么. 有人能帮忙吗?