我正在尝试将具有res.send()的人员对象从快速后端发送回有角度的前端,但是res.send()始终发送空对象。我正在使用cors将数据从localhost / 8081的express后端发送到localhost / 4200的有角前端。
表达后端
controller.js
controller.getPerson = async (req, res) => {
try{
console.log(req.body);
var result = await service.getPerson(req.body._id));
console.log(result);
res.send(result); <--- sending undefined object or nothing at all instead of result
}
catch(error)
{
console.log("controller/get_person)", error)
}
};
service.js
service.getPerson = (data) =>{;
return Person.findById({'_id':data}, function(err, docs){
console.log(docs);
return docs;
});
};
输出
{ _id: '5f126357aea7624680d07ee2' } <-- console.log(req.body)
console.log(docs)
{
_id: 5f126357aea7624680d07ee2,
first_name: 'qwer',
last_name: 'qwer',
__v: 0
}
console.log(result)
{
_id: 5f126357aea7624680d07ee2,
first_name: 'qwer',
last_name: 'qwer',
__v: 0
}
console.log(req.body)返回{_id:'someid'},console.log(docs)返回带有id的整个人员对象,console.log(result)显示与console相同的内容.log(docs)
角形前端
person-detail.component
@Input() person: Person;
getPerson(): void {
const id = this.route.snapshot.paramMap.get('id');
this.personService.getPerson(id)
.subscribe(person => this.person = person); <-- this.person is not set because person is undefined or doesn't exist
}
person.service
public getPerson(_id){
return this.http.post<Person>('http://localhost:8081/get_person', {_id});
}
前端角度错误
core.js:4081 ERROR Error: NodeInjector: NOT_FOUND [NgControl]
at getOrCreateInjectable (core.js:3819)
at Module.ɵɵdirectiveInject (core.js:13733)
at NodeInjectorFactory.NgControlStatus_Factory [as factory] (forms.js:677)
at getNodeInjectable (core.js:3913)
at instantiateAllDirectives (core.js:7973)
at createDirectivesInstances (core.js:7356)
at Module.ɵɵelementStart (core.js:13882)
at PersonDetailComponent_div_0_Template (person-detail.component.html:6)
at executeTemplate (core.js:7329)
at renderView (core.js:7138)
personService.getPerson(id)未获取person对象,因此person始终为空对象。如何解决这个问题,以便person => this.person = person使得this.person成为通过res.send()发送回去的person对象?
答案 0 :(得分:1)
您没有在服务函数中等待回调函数。
将其包装在承诺中或为findById
使用相应的承诺。
service.getPerson = (data) => {
return new Promise(resolve => {
Person.findById({'_id':data}, function(err, docs){
console.log(docs);
resolve(docs);
});
});
};