如何解决BehaviorSubject无法传递价值
在我的代码中,我有两个组件。组件1从输入获取数据,通过字符串连接组装数据,并应通过服务将其发送到组件2,在此进一步处理数据。问题在于组件2中的subscription方法从未被调用。
组件1
inputData = ''; // values assigned through template input
submit() {
console.log(this.inputData);
this.service.method(this.inputData) } //method is called when form is submitted
服务
dataSubject = new BehaviorSubject<string>('');
data$ = this.dataSubject.asObservable();
method(data) {
this.dataSubject.next(data); }
console.log(this.inputData);
组件2
insertedData = '';
method() {
this.service.data$.subscribe(
data => this.insertedData = data,error => console.error(error))
console.log('here is the data' + this.insertedData) } method is called when a button from that component is pushed
一切正常,在Component1和我可以控制台的服务中运行。记录来自用户输入的数据。但是当到达component2时,数据不存在,只有初始值''(空字符串)被console.logged。那是因为订阅永远不会发生。 (我也尝试过只在console.log消息那里查看它是否在其中运行,但是什么也没发生,所以我认为订阅永远不会执行)。另一方面,也没有错误消息可以帮助我识别问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。