首页 > 解决方案 > 绑定到服务变量的 AngularJS 1.6.9 控制器变量不会改变

问题描述

我有 2 个组件都在访问服务。一个组件传递一个对象,另一个组件应该显示它或只是接收它。问题是初始化过程完成后,显示组件中的变量不会改变。

我尝试使用$scope$scope.$apply()this.$onChanges以及$scope.$watch来跟踪变量,但它始终保持不变。

来自显示组件的此控制器在对象中提供来自输入字段的文本。

app.controller("Test2Controller", function ($log, TestService) {

    this.click = function () {
        let that = this;
        TestService.changeText({"text": that.text});
    }
});  

这就是服务,它获取 objekt 并将其保存到this.currentText中。

app.service("TestService", function ($log) {

    this.currentText = {};

    this.changeText = function (obj) {
        this.currentText = obj;
        $log.debug(this.currentText);
    };

    this.getCurrentText = function () {
        return this.currentText;
    };

});  

这是应该显示对象的控制器,但甚至无法更新this.text变量。

app.controller("TestController", function (TestService, $timeout, $log) {

    let that = this;

    this.$onInit = function () {
        this.text =  TestService.getCurrentText();
        //debugging
        this.update();
    };

    //debugging
    this.update = function() {
        $timeout(function () {
            $log.debug(that.text);
            that.update();
        }, 1000);
    }

    //debugging
    this.$onChanges = function (obj) {
        $log.debug(obj);
    }


});  

我花了很多时间寻找答案,但大多数都与指令有关,或者在我的情况下不起作用,例如将对象放入另一个对象的一种解决方案。我想我可以使用$broadcast$on但我听说要避免使用它。我使用的角度版本是:1.6.9

标签: angularjsangularjs-serviceangularjs-controllerangularjs-components

解决方案


我发现你的方法有问题。您正在尝试共享对象的单一引用。您希望共享一次对象引用,并希望在使用它的任何地方都反映它。但是按照changeText方法,您正在设置对currentText服务属性的新引用,这是错误的。

相反,我建议您只使用一个对象的单一引用,它将负责在多个控制器之间共享对象。

服务

app.service("TestService", function ($log) {
    var currentText = {}; // private variable
    // Passing text property explicitly, and changing that property only
    this.changeText = function (text) {
        currentText.text = text; // updating property, not changing reference of an object
        $log.debug(currentText);
    };
    this.getCurrentText = function () {
        return currentText;
    };
});

现在 fromchangeText方法只是传递text需要更改为,而不是新对象。


推荐阅读