【问题标题】:Angular 4 how to update value of class within callback function? [duplicate]Angular 4如何在回调函数中更新类的值? [复制]
【发布时间】:2018-01-05 22:07:00
【问题描述】:

我有这个代码,其中我的“this.index”和“this.result”是未定义的,我如何制作它以便当我更新它们的值时它就像通过引用传递一样:

  submitQuiz(addsMemberPoints, pointsCallback) {
    this.getValues(this.answers, this.totalPoints, this.index, function(answers, totalPoints, ranks, index){
      pointsCallback(answers, ranks, addsMemberPoints, totalPoints, index, function(index, points){
        function getMember(obj) {
          return Object.keys(obj).reduce(function(a, b){ return obj[a] > obj[b] ? a : b });
        }
        // would like to change index and result of initial class with new values
        this.result = getMember(points);
        this.index = index;
      });
    });

  }

产生的错误被重现

【问题讨论】:

    标签: javascript angular typescript pass-by-reference


    【解决方案1】:

    通过使用“那个”技巧。

    submitQuiz(addsMemberPoints, pointsCallback) {
        var that = this;
    
        this.getValues(this.answers, this.totalPoints, this.index, function(answers, totalPoints, ranks, index){
          pointsCallback(answers, ranks, addsMemberPoints, totalPoints, index, function(index, points){
            function getMember(obj) {
              return Object.keys(obj).reduce(function(a, b){ return obj[a] > obj[b] ? a : b });
            }
            // changed this to that
            that.result = getMember(points);
            that.index = index;
          });
        });
    
      }
    

    【讨论】:

      【解决方案2】:

      为什么不使用arrow functions

      箭头函数不会丢失当前的this 上下文,允许您在不定义thatself 变量的情况下访问它。

      查看这个 ES6 示例并查看 getCommaSaperatedImages 函数 -

      class Hotel {
      
        constructor(images) {
          if (images && images.length) {
            this.images = images;
          }
        }
      
        getCommaSaperatedImages() {
          this.imageString = "";
          if (this.images && this.images.length) {
            this.images.forEach((image, index, images) => {
              //notice here `this` is still pointing to `Hotel` class.
              this.imageString += image.url;
              if (index === images.length - 1) {
                return;
              }
              this.imageString += ", ";
            });
          }
          return this.imageString;
        }
      }
      
      let hotel = new Hotel([{
        id: 1,
        url: 'http://image1.png'
      }, {
        id: 2,
        url: 'http://image2.png'
      }]);
      
      console.log(hotel.getCommaSaperatedImages());

      Typescript 应该完全一样。

      我希望这会有所帮助:)。

      【讨论】:

      • 这是一个正确的答案,但由于这是一个已经回答的基本问题,最好将其标记为重复,这样我们就不会有多个相同事实的来源跨度>
      • 有道理!谢谢!!
      • @JuanMendes 我认为我的声誉不足以将问题标记为重复。 :|
      • 我知道,有时新人很想留下答案以绕过 SO 施加的一些限制。但在大多数情况下,限制是有原因的:)
      猜你喜欢
      • 1970-01-01
      • 2020-12-03
      • 1970-01-01
      • 2020-11-11
      • 2016-01-14
      相关资源
      最近更新 更多