Angular 5-订阅行为主体时出现的问题

时间:2018-06-26 09:24:16

标签: rxjs angular5 observable behaviorsubject

在一个服务的构造函数中订阅行为Subject变量时遇到问题。订阅首次发生,当 ok的值为0 ,但是当我在执行服务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();
      }

    });
}

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

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

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

找到工作代码