数据未在视图中更新

时间:2019-07-27 22:31:21

标签: javascript node.js angular ionic-framework mean-stack

我在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
    });
  });
};

1 个答案:

答案 0 :(得分:0)

我认为问题出在您的后端。我可以看到您正在从解码的令牌发送数据,并且登录时令牌已编码,因此它没有更新的数据。

res.status(200).json({
  err: null,
  msg: "Name was updated successfully.",
  data: req.decodedToken.user.name
});

您能告诉我调用方法“ getUserNamePoints();”时如何从后端检索用户数据吗? ?您是在数据库中还是在已解码的令牌中寻找用户数据?