这个问题可能是由于Angular截取了Subject更新前的值,从而导致更新后的值无法正确地传递。您可以通过将.ngZone.run(() => {})包装在.next(value)调用内部来解决这个问题。
例如:
import { Injectable, NgZone } from '@angular/core'; import { BehaviorSubject } from 'rxjs';
@Injectable() export class TestService { private subject = new BehaviorSubject(null);
constructor(private ngZone: NgZone) {}
updateValue(value: any): void { this.ngZone.run(() => { this.subject.next(value); }); }
getValue() { return this.subject.getValue(); } }
在代码中,我们使用Angular的.ngZone来运行.next(value)方法,从而更新Subject,并确保正确的值正确地传递到订阅器。 通过这种方式,可以解决这个问题并正常地使用行为主题。