简体   繁体   English

主题值更改时不会触发订阅

[英]Subscribe not being triggered when the subject values changes

I have two components A and B, and when an event occurs in A, I need to get the updated value in B in which I am subscribing to a service to get the latest value from A.我有两个组件 A 和 B,当 A 中发生事件时,我需要在 B 中获取更新的值,我在其中订阅了一项服务以从 A 获取最新值。

component A:组分A:

sendString(inputEntered){  //happens when on buttonclick
....
this.myService.sendRecent(inputEntered);
}

Service:服务:

export class myService {
  private inputStringSource = new Subject<string>();
  public inputString$ = this.inputStringSource.asObservable();
  constructor() {}


  sendRecent(inputString: string) {
    this.inputStringSource.next(inputString);
  }

component B:组分 B:

... ...

  ngOnInit(): void {

    this.myService.inputString$.subscribe(data => {
      console.log("input value ", data);
    });

Service is receiving new value but the subscription in component B is not being triggered.. what am I doing wrong here?服务正在接收新值,但未触发组件 B 中的订阅。我在这里做错了什么? Please let me know.请告诉我。 Tried few option but still no luck.尝试了几个选项,但仍然没有运气。

I think the problem might be with how you are importing service in your component.我认为问题可能在于您如何在组件中导入服务。 Now, since we don't have complete code reference, please make sure the module where you have put component B should not have service(myService in your example) in the providers list.现在,由于我们没有完整的代码参考,请确保您放置组件 B 的模块在提供者列表中不应该有服务(在您的示例中为 myService)。 BehaviourSubject subscribe works when the service is not explicitly mentioned in the providers of parent module.当服务未在父模块的提供者中明确提及时,BehaviourSubject 订阅有效。

如果您在订阅组件 B 之前从组件 A 发送数据,则可能会发生这种情况,您可以尝试使用 ReplaySubject

private inputStringSource = new ReplaySubject<string>();

Change this and try:改变这一点并尝试:

import { BehaviorSubject } from 'rxjs';

private inputStringSource = new BehaviorSubject<string>('');

If it doesn't works, try this change the service like this:如果它不起作用,请尝试像这样更改服务:

export class myService {

  private inputStringSource = new Subject<string>();

  public get inputString$() {
     return this.inputStringSource.asObservable();
  }
  
  constructor() {}


  sendRecent(inputString: string) {
    this.inputStringSource.next(inputString);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM