我正在从Angular应用程序向node.js服务器发出请求,需要等到服务器收到响应后再继续。我的异步调用似乎出了点问题,但是我不知道这是什么。
这是我的登录组件:
onLogin() {
if (this.form.invalid) {
console.log(this.form);
console.log('Form invalid');
return;
}
this.isLoading = true;
const findUserType = () => {
return new Promise(resolve => {
resolve(this.authService.getUserType(this.form.value.username));
});
};
async function asyncCall() {
console.log('getting user type');
const result = await findUserType().then(userType => {
console.log(userType);
});
}
通过authservice进行请求:
getUserType(username: string) {
this.http.post<{ message: string; }>(
'http://localhost:3000/api/user/find-user',
{ username }
)
.subscribe(response => {
console.log(response.message);
return response.message;
});
}
哪个是从nodejs抓取数据:
router.post('/find-user', (req, res, next) => {
function checkHauler() {HaulerUser.countDocuments({ username: req.body.username }, function (err, count) {
if (count > 0) {
return res.status(200).json({
message: 'isHauler'
})
}
});
}
function checkAbf() {AbfUser.countDocuments({ username: req.body.username }, function (err, count) {
if (count > 0) {
return res.status(200).json({
message: 'isAbf'
})
}
});
}
function checkUtility() {UtilityUser.countDocuments({ username: req.body.username }, function (err, count) {
if (count > 0) {
return res.status(200).json({
message: 'isUtility'
})
}
});
}
Promise.all([checkHauler(), checkAbf(), checkUtility()])
.then(() => {
console.log('done')
})
这是我的控制台中显示的内容:
getting user type
undefined
result: undefined
Uncaught TypeError: Cannot read property 'type' of undefined
at setFieldValue (onloadwff.js:71)
at HTMLFormElement.formKeydownListener (onloadwff.js:71)
isAbf
我对此非常陌生,任何帮助将不胜感激!
答案 0 :(得分:0)
您正在将可观察性和承诺结合在一起,如果您刚开始,这将使这些概念变得更加难以掌握。
我的建议是让getUserType
兑现承诺,像这样:
getUserType(username: string) {
return this.http.post(
'http://localhost:3000/api/user/find-user',
{ username }
).toPromise();
}
然后在其他功能中,您可以记录此POST请求的结果:
async yourAsyncCall() {
console.log('getting user type');
const result = await this.authService.getUserType('blahh insert test username here');
console.log('post api result', result);
}
请注意,我已取消使用.then
来支持异步/等待。 Hackernoon写了good article,说明了为什么异步/等待使承诺更加容易使用。