当在 Angular 9 中多次订阅一个行为主体的单个 next 时,可以采用以下方法解决:
1.使用 pipe(share):
share 算子可让订阅者共享 obervable 的执行结果,从而减少多余的订阅。使用该算子可以避免多次触发 next。
import { BehaviorSubject } from 'rxjs'; import { share } from 'rxjs/operators';
export class MyComponent {
myBehaviorSubj = new BehaviorSubject
getData() { return this.http.get('my/api/endpoint').pipe( share() ); }
myMethod() { this.getData().subscribe(response => { console.log(response); this.myBehaviorSubj.next(response.someProperty); }); } }
2.取消先前的订阅:
如果您确实需要多次订阅单个 next,但每次订阅前都要取消先前的订阅。这样可确保只有一个订阅者会收到通知。
import { BehaviorSubject } from 'rxjs';
export class MyComponent {
myBehaviorSubj = new BehaviorSubject
myMethod() { if (this.subscription) { // 取消前一个订阅 this.subscription.unsubscribe(); }
const newSub = this.myBehaviorSubj.subscribe(value => {
console.log(value);
});
this.myBehaviorSubj.next('new value');
this.subscription = newSub; // 将新的订阅存储到组件的变量中
} }