我正在使用 Angular 工作,只想在某些值排列时显示某种形式。我有后端路由工作并与 postman 进行了测试。这是我的代码
Blockquote Angular Component HTML
<div *ngIf="canEdit()">
...
</div>
^ 是当前唯一调用该函数的东西
Blockquote Angular TS File
canEdit() {
let username = this.currentUser.user.username;
let values = {
"_id": this.org._id,
"user": username
}
return this.http.post<any>('http://localhost:3001/users/compareUser', values, { withCredentials: true }).subscribe(
result => {
if (result.message == "All good!") {
console.log(result);
return true;
} else {
return false;
}
}
)
所以这是两个部分,目前如果我运行它,它会导致 console.log(result) 的无限循环,它显示 {result: "All Good!"} 我也会分享我的后端路线,这是 express 。有趣的是,如果我只是替换函数 canEdit() 以返回 true,也许 console.log 一些文本,这样我就可以看到它被调用了多少次,它只被调用一次。然而,使用我共享的代码(TS),它甚至从未承认 console.log(result) 下面的“返回 true”。
Express route
router.post("/compareUser", function(req, res, next) {
let token = req.cookies.token;
let id = req.body._id;
let user = req.body.user;
if (token) {
Org.findById(id, (err, result) => {
if (err) {
console.log(err);
return res.status(401).json({
message: "Could not find Organization"
});
} else {
User.findOne({ username: user }).then(user => {
if (!user) {
return res.status(401).json({
message: "Are you sure you exist?"
});
} else {
if (user.username == result.username) {
return res.status(200).json({
message: "All good!"
});
}
}
});
}
});
} else {
return res.status(404).json({
message: "You must be logged in"
});
}
});
最佳答案
您在 canEdit() 方法中返回订阅而不是 bool 值,您可以通过向组件类添加变量并使用该变量而不是方法来解决此问题:
valid = false;
ngOnInit() {
this.canEdit();
}
canEdit() {
let username = this.currentUser.user.username;
let values = {
"_id": this.org._id,
"user": username
}
this.http.post<any>('http://localhost:3001/users/compareUser', values, { withCredentials: true }).subscribe(
result => {
if (result.message == "All good!") {
console.log(result);
this.valid = true;
} else {
this.valid = false;
}
}
)
}
并在您的模板中:
<div *ngIf="valid"></div>
关于javascript - *ngIf 创建无限循环并且永远不会解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59806421/