2015-12-27 48 views
0

我正在使用angular-fullstack来创建应用程序。在我的应用程序,我使用Yelp API来获取搜索结果,我想在一个变量来存储(注:this.searchTerm通过一个NG-模型改变了HTML):Angular 2 Promises?

'use strict'; 

(function() { 

class MainController { 

    constructor($http) { 
    this.$http = $http; 
    this.awesomeThings = []; 
    this.searchTerm = ""; 
    this.data = []; 
    } 

    addThing() { 
    this.$http.get('/api/messages/city/' + this.searchTerm).success(function(res){ 
     this.data = res; 
    }); 
    }; 
} 

angular.module('nightlifeApp').controller('MainController', MainController);})(); 

当我做所以,我得到一个错误,this.data没有定义。我知道这是对异步调用的性质做的,但我该如何解决这个问题?

由于

+0

你如何调用addThing()方法? –

+0

它通过在HTML中的按钮上单击鼠标来调用。 – svsav

回答

0

this关键字将在严格模式下.then函数内不确定的。设置一个局部变量来引用then函数中的this绑定。

'use strict'; 

(function() { 

class MainController { 

    constructor($http) { 
    this.$http = $http; 
    this.awesomeThings = []; 
    this.searchTerm = ""; 
    this.data = []; 
    } 

    addThing() { 
    var self = this; 
    this.$http.get('/api/messages/city/' + this.searchTerm).then (function(res){ 
     self.data = res.data; 
    }); 
    }; 
} 

angular.module('nightlifeApp').controller('MainController', MainController);})(); 

另外,.success方法是弃用。改为使用.then