【问题标题】:angular/javascript not recognizing global variable inside function角度/javascript无法识别函数内的全局变量
【发布时间】:2015-03-05 22:22:00
【问题描述】:

我做了一项服务,可以从 omdb api 获取电影信息,但是当我尝试从控制器使用它并将结果推送到我的电影数组时,它会抱怨

TypeError: 无法读取未定义的属性“push”

.controller('AppCtrl', function(omdbApi) {
    this.movie = [];
    this.getMovie = function(title, year) {
        year = typeof year === 'undefined' ? "" : year;
        omdbApi.getMovie(title, year).then(function(data){
            this.movie.push({
                poster: data.data.Poster,
                title: data.data.Title,
                actors: data.data.Actors,
                plot: data.data.Plot
            });
        });
    }
});

有人可以解释为什么它无法推送到电影吗?我不确定这是一个角度问题,但从javascript的角度来看,我真的不明白。我已经测试过传入的数据是合法的。 如果我只是将数据分配给电影,那么我无法在函数之外访问它。

【问题讨论】:

  • this 不是您想象的那样,因此没有 movie 属性。

标签: javascript angularjs


【解决方案1】:

这是一个常见的错误。 this 回调中的 this 对象与 .controller() 回调中的对象不同。使用闭包:

.controller('AppCtrl', function(omdbApi) {
    var self = this; // <---- this is the key
    this.movie = [];
    this.getMovie = function(title, year) {
        year = typeof year === 'undefined' ? "" : year;
        omdbApi.getMovie(title, year).then(function(data){
            self.movie.push({
                poster: data.data.Poster,
                title: data.data.Title,
                actors: data.data.Actors,
                plot: data.data.Plot
            });
        });
    }
});

另一种选择是使用Function.prototype.bind() 强制上下文。

【讨论】:

  • 谢谢!这解决了问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-23
  • 2017-03-27
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多