为什么'这个'无法解决AngularJS中的服务?

时间:2016-01-21 10:49:21

标签: javascript jquery angularjs ecmascript-6 babeljs

我正在使用带有Babble的ES6来使用angular1.x构建一个角度应用程序。当我使用Ajax调用服务时,控制器中有一个变量未解析。

控制器

    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 个答案:

答案 0 :(得分:8)

this取决于函数上下文。

this保存在that

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

如评论中所述,您可以改为使用箭头语法:

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