首页 > 解决方案 > 订阅行为主题不适用于所有组件

问题描述

我是我的全球服务我创建了一个behaviourSubject 变量

数据工作流服务

export class CallWorkflowService {
  url = 'http://localhost:3000/';
  selectedNode : BehaviorSubject<Node> = new BehaviorSubject(new Node(''))
  dataflow : BehaviorSubject<any> = new BehaviorSubject<any>({});

  constructor(private http: HttpClient) {}
  getDataflow() {
    return this.http.get(this.url);
  }
  updateNode(node :Node) {
    this.selectedNode.next(node);
  }
}

在我的组件ReteComponent我使用设置 behaviorSubject 值

this.dataFlowService.selectedNode.next(node);

我订阅了 BehaviourSubject 的第二个组件

export class ComponentsMenuComponent implements OnInit {

constructor(private callWorkflowService:CallWorkflowService) { }
selectedNode:Node = new Node('');
dataFlow:any;
nxtElements:String[]=[]

ngOnInit() {


    this.callWorkflowService.dataflow.subscribe(data=> {
      this.dataFlow=data
    })
    this.callWorkflowService.selectedNode.subscribe( (node) => {
      this.selectedNode=node; <=== ###### Subscription is not triggered
      if(this.dataFlow) {
        this.nxtElements=this.dataFlow[node.name].next;
      }

    })
  }

当我触发selectedNode订阅的新价值时不起作用

但在另一个组件中它运行良好

export class AppComponent {
  opened:boolean=false;
  events: string[] = [];
  constructor(private callWorkflowService:CallWorkflowService) { }

  ngOnInit() {
    this.callWorkflowService.selectedNode.pipe(
      skip(1)
    )
    .subscribe( (node) => {
      this.opened=true; <== subscription is working
    })
  }
}

当我将其更改为时,我注意到在ComponentsMenuComponent中

export class ComponentsMenuComponent implements OnInit {

constructor(private callWorkflowService:CallWorkflowService) { }
selectedNode:Node = new Node('');
dataFlow:any;
nxtElements:String[]=[]

ngOnInit() {
     this.callWorkflowService.getDataflow().subscribe(data=> {
       this.dataFlow=data;
     }) ####CHANGE HERE ### <== using `getDataFlow` method which is not observable
    this.callWorkflowService.selectedNode.subscribe( (node) => {
      this.selectedNode=node; ### <=== subscription is triggered
      if(this.dataFlow) {
        this.nxtElements=this.dataFlow[node.name].next;
      }

    })
  }

selectNode 订阅正在运行。

更新 我试图改变我的前进方式

在我的服务中,我添加了一个返回最后一个值的方法

updateDataFlow() {
  return this.dataflow.getValue();
}

ComponentsMenuComponent

this.callWorkflowService.node.subscribe( (node) => {
  this.dataFlow = this.callWorkflowService.updateDataFlow();
  this.selectedNode=node;
  if(this.dataFlow) {
    this.nxtElements=this.dataFlow[node.name].next;
  }

})

这里再次订阅不起作用..

我试图评论这条线

this.dataFlow = this.callWorkflowService.updateDataFlow(); 在这里惊喜..订阅有效。

我不知道为什么当我取消注释我提到的行时它不订阅

标签: javascriptangularrxjssubscriptionbehaviorsubject

解决方案


您必须错误地提供 CallWorkflowService 并在不同组件中获取不同的服务实例。如果一个组件正在工作而另一个组件没有工作,那么我猜想它们不是都订阅了相同的行为主题。

您如何提供服务?它是在模块、组件中提供的,还是您在使用中提供的?


推荐阅读