简体   繁体   English

angular / javascript无法识别函数内部的全局变量

[英]angular/javascript not recognizing global variable inside function

I did a service that gets me a movie info from omdb api but when I'm trying to use it from my controller and push the result to my movie array it complains about 我提供了一项从omdb api获取电影信息的服务,但是当我尝试从控制器使用它并将结果推送到我的电影数组时,它会抱怨

TypeError: Cannot read property 'push' of undefined 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
            });
        });
    }
});

Can someone explain why is it unable to push to movie? 有人可以解释为什么它不能上电影吗? I'm not sure it's an angular problem but from javascript point I really don't get it. 我不确定这是一个有角度的问题,但是从javascript的角度来看,我真的不明白。 I've tested that the incoming data is legit. 我测试了传入的数据是否合法。 If I just assign the data to movie then I'm unable to access it outside the function. 如果我只是将数据分配给电影,那么我将无法在函数外部访问它。

This is a common mistake. 这是一个常见的错误。 this object in your .then() callback does not refer to the same object of .controller() callback. this对象在你的.then()回调并非指的同一对象.controller()回调。 Use a closure: 使用闭包:

.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
            });
        });
    }
});

Another option is to use Function.prototype.bind() to force a context. 另一个选择是使用Function.prototype.bind()强制上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM