【问题标题】:Data does not update in view数据未在视图中更新
【发布时间】: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 =&gt; { console.log(data); this.getUserNamePoints(); }, error =&gt; { this.updateFail(); } );

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


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2017-09-27
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2015-06-26
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多