javascript - *ngIf 创建无限循环并且永远不会解析

标签 javascript angular typescript express

我正在使用 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/

相关文章:

javascript - 卡在等待 s3.listObjects 上

angular - 如果 POST 失败,如何恢复 Angular 2 应用程序中的数据

Angular 10/ typescript : What is the difference between how the same property of an object is being assigned

javascript - 无法通过 ngSwitch 正确使用枚举

javascript - 当我的重定向 URL 包含唯一用户 ID 时,如何使用 OneDrive Web 选取器?

javascript - AngularJS 指令 - 指定回调的默认值

javascript - 使用 jquery ajax 的两个 CORS 请求之间的时间间隔

Angular2 Router - 有条件地隐藏链接

html - 从 Angular 8 升级到 12 后出现错误 - "Property ' 类型 'AbstractControl' 上不存在控件”

reactjs - 没有 withStyles 的 material-ui@next?