【发布时间】: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