angularjs - 绑定到服务变量的 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
解决方案
我发现你的方法有问题。您正在尝试共享对象的单一引用。您希望共享一次对象引用,并希望在使用它的任何地方都反映它。但是按照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
需要更改为,而不是新对象。
推荐阅读
- dart - 如何在颤振应用程序中返回应用程序的第一页?
- javabeans - java.lang.NullPointerException:在独立应用程序中自动装配 bean 时为空
- dom - WebDriver 不可见 DocumentFragment 元素
- android - Kotlin 从嵌套类中引用外部类
- python - 移动 app.py 和静态文件夹后,Flask 无法解析静态文件
- string - 从字符串中获取具有字符索引的子字符串
- android - 我如何知道应用程序在不同的国家/地区启动/更新
- php - Laravel - 验证数组输入请求数据在数据库中的唯一性
- ruby-on-rails - 确保随机生成的字符串是唯一的
- python-3.x - 为什么类不能充当 Python 中函数的封闭空间