【问题标题】:Angular 5 - Issue while subscribing the Behavior SubjectAngular 5 - 订阅行为主题时的问题
【发布时间】:2018-06-26 09:24:16
【问题描述】:

在一项服务的构造函数中订阅行为主题变量时遇到问题。当 ok 的值为 0 时第一次发生订阅,但是当我在 service 1 中执行 .next(1) 时,订阅为服务 2 的构造函数中没有发生。

Service 1 : Where behavior subject variable is emitting

 counter: number = -1;
 ok: BehaviorSubject<any> = new BehaviorSubject(0);
  if (this.counter === 0) {
      setTimeout(() => {
        this.checkCounterFinally();
      }, 1000);
    }
  }

  checkCounterFinally() {
    if (this.counter === 0) {
      this.ok.next(1);

    }

  }

Service 2: Where i am subscribing the behavior subject variable in constructor.

constructor(private service: Service1){
    this.service.ok.subscribe((val) => {
      console.log("service2", val);
      if (val=== 1) {
        this.getDataFromLocalStorage();
      }

    });
}

【问题讨论】:

  • 你能用最少的代码创建一个 plunker 吗?我认为主要问题是您直接使用主题而不是返回可观察对象(通过asObservable()),但很难确定。

标签: rxjs angular5 observable behaviorsubject


【解决方案1】:

BehaviorSubject 的使用看起来不错。您的问题的根源可能是您的应用中有许多 Service1 实例。

【讨论】:

  • 嗨 Mohamed,感谢您的回复。我对某些功能做了同样的事情。它在那里工作得很好。此外,我这里只有服务 1 的实例。
【解决方案2】:

您需要从组件中调用 next 方法,如下所示。

constructor(private service: Service) {
     this.service.checkCounterFinally(); 
   }

像这样更改服务。

import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { Injectable } from '@angular/core';

@Injectable()
export class Service {
   counter: number = -1;
    ok: BehaviorSubject<number> = new BehaviorSubject(0);
    selectedSubjectObsv = this.ok.asObservable();

     constructor() { 
if (this.counter === 0) { 
      setTimeout(() => {
        this.checkCounterFinally();
      }, 1000);
    } 
  }


     checkCounterFinally() {
   // if (this.counter === 0) {
      this.ok.next(1);

   // }

  }
}

在这里找到工作代码https://stackblitz.com/edit/angular-wwt91u

【讨论】:

  • 嗨 Supun,感谢您的回复。但不幸的是,根据要求,我不必使用相同的组件。它仅使用行为主体进行服务之间的通信。任何建议。
  • 我使用了单个组件,仅用于演示目的。您仍然可以使用多个组件。请参阅 stackblitz 中的更新代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
相关资源
最近更新 更多