【发布时间】:2019-09-09 20:37:38
【问题描述】:
我正在我的 ionic 4 前端中创建一个更新函数,它有一个更新用户信息的表单。例如,当我尝试更改名称时,它会在数据库中更新,但不会通过插值显示在视图中,除非我注销并重新登录。这是我在前端的更新方法。
updateInfo() {
if (!this.updateForm.valid) {
this.invalidUpdate();
} else {
if (!(this.name === "")) {
var nameObj = {
name: this.name
};
this._userService.updateName(nameObj).subscribe(
data => {
console.log(data);
this.getUserNamePoints();
},
error => {
this.updateFail();
}
);
}
};
this.getUserNamePoints();
}
}
这里是服务中的updateName(name)方法
updateName(name) {
var headers = new Headers();
headers.append(
"Authorization",
"Bearer " + this._authService.getAuthorizationToken()
);
headers.append("Content-Type", "application/json");
return this.http
.post(environment.apiUrl + "/user/updateName", name, {
headers
})
.map(res => res.json());
}
这是getUserNamePoints()的方法,在构造函数中也被调用:
getUserNamePoints() {
this._authService.getPoints().subscribe((res: any) => {
this.current = res.data;
this.clientName = res.name;
});
}
这是我正在执行的插值:
<h2>
<ion-text color="secondary" style="font-weight:bold">
Hello, {{ clientName }}!</ion-text
>
</h2>
这是我的后端方法:
module.exports.updateName = function(req, res, next) {
User.findByIdAndUpdate(
req.decodedToken.user._id,
{
$set: req.body
},
{ new: true }
).exec(function(err, updatedUser) {
if (err) {
return next(err);
}
res.status(200).json({
err: null,
msg: "Name was updated successfully.",
data: req.decodedToken.user.name
});
});
};
【问题讨论】:
-
在您发送更新名称的请求后,您会立即获得更新后的名称 (getUserNamePoints())。 在之后调用它,您知道请求已被处理,即在接收更新响应的回调中。否则,您无法保证 get 请求不会在更新请求之前或同时处理。
-
@JBNizet 我在回调中调用 getUserNamePoints() 方法:
this._userService.updateName(nameObj).subscribe( data => { console.log(data); this.getUserNamePoints(); }, error => { this.updateFail(); } );
标签: javascript node.js angular ionic-framework mean-stack