订阅BehaviorSubject直到未定义值

时间:2019-06-18 09:24:27

标签: angular typescript rxjs

我有一个值为BehaviorSubject的服务。我正在TS页面中通过服务访问此值。我使用这段代码:

基本上,如果SubjectVariable不是未定义的,我将此值添加到我的SubjectVariableNew的本地变量中。 我想循环直到SubjectVariable!== undefined持续3秒。如果在这段时间内未定义,我会弹出一条短信。所以基本上我想有3秒的时间窗口/加载时间,并检查SubjectVariable!==未定义。

this.myService.mySubjectVariable.subscribe((SubjectVariable: 
string) => {     
            if (SubjectVariable !== undefined) {
                this.SubjectVariableNew = SubjectVariable;
                this.valueIsReturned = true;
            } else {
                this.valueIsReturned = false;
            }

});

2 个答案:

答案 0 :(得分:1)

使用timeoutfilter运算符:

    const subject = new BehaviorSubject(null);
    subject
      .pipe(
        filter(data => data !== null)
      )
     .pipe(
        timeout(3000),
        catchError(error => of(`Request timed out!`))
      )
      .subscribe(
        () => console.log("Data is not null")
      );

答案 1 :(得分:1)

您可以使用retryWhen延迟重试。这是一个示例:

const sub = new rxjs.BehaviorSubject(undefined);

setTimeout(() => sub.next('Hey'), 1500);

sub.pipe(
  rxjs.operators.map(value => {
    if (value) return value;
    throw 'Error: value is undefined';
  }),
  rxjs.operators.retryWhen(errors => errors.pipe(
    rxjs.operators.tap(error => console.log('retrying for error = ', error)),
    rxjs.operators.delay(1000),
    rxjs.operators.take(2),
  ))
).subscribe(
  value => console.log('value has been set'),
  error => console.log('value has been kept to undefined'),
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.2/rxjs.umd.js"></script>