2016-01-21 53 views
2

我使用ES6與Babble構建使用angular1.x的角度應用程序。當我使用Ajax調用服務時,控制器中有一個變量未解決。爲什麼'this'無法在AngularJS的服務中解決?

控制器

export default class MenuController { 
    constructor(MenuService) { 
     this.Items=[]; 
     this.MenuService = MenuService; 
    } 

    getMenu() { 
     this.MenuService.getMenuItems().then(function(data) { 
      this.Items = data 
     }); 
     console.log(this.Items) 
    } 
} 

MenuController.$inject = ['MenuService']; 

服務

class MenuService { 
    constructor($http) { 
     this.$http = $http; 
    } 

    getMenuItems() { 
     var promise = null; 
     if (!promise) { 
      promise = this.$http.get('./data/menu-config.json').then(function(response) { 
       return response.data; 
      }); 
     } 
     return promise; 
    } 
} 

    MenuService.$inject = ['$http']; 

    export default angular.module('services.menu-service', []) 
     .service('MenuService', MenuService) 
     .name; 

現在,每當這個代碼被執行,我得到瀏覽器控制檯上看到以下錯誤。

TypeError: Cannot set property 'Items' of undefined 
    at eval (menu.ctrl.js:23) 
    at processQueue (angular.js:14792) 
    at eval (angular.js:14808) 
    at Scope.$eval (angular.js:16052) 
    at Scope.$digest (angular.js:15870) 
    at Scope.scopePrototype.$digest (hint.js:1972) 
    at Scope.$apply (angular.js:16160) 
    at Scope.scopePrototype.$apply (hint.js:2035) 
    at done (angular.js:10589) 
    at completeRequest (angular.js:10787)(anonymous function) @ angular.js:12520(anonymous function) @ angular.js:9292processQueue @ angular.js:14800(anonymous function) @ angular.js:14808Scope.$eval @ angular.js:16052Scope.$digest @ angular.js:15870scopePrototype.$digest @ hint.js:1972Scope.$apply @ angular.js:16160scopePrototype.$apply @ hint.js:2035done @ angular.js:10589completeRequest @ angular.js:10787requestLoaded @ angular.js:10728 

我不能糾正這一點。而我知道有一些參考錯誤。請幫助

+1

使用箭頭函數['()=> {}'](HTTPS: //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)而不是'function' – Hacketo

+0

我不認爲這是問題,因爲Bable是向後兼容的,並且生成的腳本非常好! –

+0

@Hacketo是所有瀏覽器的箭頭函數嗎? –

回答

8

this取決於功能上下文。

保存thisthat

var that = this; 
this.MenuService.getMenuItems().then(function(data) { 
     that.Items = data 
}); 

正如註釋所提到的,可以使用代替箭頭語法:

this.MenuService.getMenuItems().then(data=>this.Items = data); 
+0

非常感謝。我知道Bable生成了這個。你得到了正確的。 –

相關問題