【问题标题】:Why is the 'this' not able to resolve within the service in AngularJS? [duplicate]为什么'this'不能在AngularJS的服务中解决? [复制]
【发布时间】:2025-12-12 01:00:01
【问题描述】:

我正在使用 ES6 和 Babble 来构建一个使用 angular1.x 的 Angular 应用程序。当我使用 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

我无法纠正这一点。而我知道存在一些参考错误。请帮忙

【问题讨论】:

  • 使用箭头函数() => {}代替function
  • 我认为这不是问题,因为 Bable 向后兼容并且生成的脚本非常好!
  • @Haketo 箭头功能适用于所有浏览器吗?
  • @ParthTrivedi 我猜 babel 会完成这项工作,它是 es6。我链接了 mdn doc 你可以看到浏览器支持
  • @ShivKumarGanesh 箭头功能让你使用this

标签: javascript jquery angularjs ecmascript-6 babeljs


【解决方案1】:

this 取决于函数上下文。

this 保存到that

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

如 cmets 中所述,您可以改用箭头语法:

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

【讨论】:

  • 非常感谢。我知道 Bable 生成了这个。你选对了。