【问题标题】:AngularJS 1.6.9 controller variable bound to service variable doesn't change绑定到服务变量的 AngularJS 1.6.9 控制器变量不会改变
【发布时间】:2019-03-05 23:21:04
【问题描述】:

我有 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});
    }
});  

这是服务,它获取对象并将其保存到 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

【问题讨论】:

    标签: angularjs angularjs-service angularjs-controller angularjs-components


    【解决方案1】:

    我发现你的方法有问题。您正在尝试共享对象的单一引用。您希望共享一次对象引用,并希望在使用它的任何地方都反映它。但是按照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;
        };
    });
    

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

    【讨论】:

      猜你喜欢
      • 2014-09-05
      • 1970-01-01
      • 2016-09-02
      • 1970-01-01
      • 2014-01-24
      • 2014-05-09
      • 2014-05-01
      • 2016-06-05
      • 1970-01-01
      相关资源
      最近更新 更多