2

I am using ES6 with Babble for constructing an angular app using angular1.x. There is a variable in the controller which is not resolved when I call a Service using Ajax.

Controller

    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'];

Service

    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;

Now whenever this code is executed I get the following error on the browser console.

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

I am not able to rectify this. Whereas I know that there is some referential error. Please help

Shiv Kumar Ganesh
  • 3,799
  • 10
  • 46
  • 85

1 Answers1

8

this depends on the function context.

Save this in that:

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

As mentioned in comments, you can use arrow syntax instead:

 this.MenuService.getMenuItems().then(data=>this.Items = data);
Michael Kang
  • 52,003
  • 16
  • 103
  • 135