Rah*_*hul 0 rxjs typescript angular-services angular
这是非常神秘的,我的订阅被多次触发 - 我不知道我的错误是什么 - 我在另一个人身上遵循了相同的方法,但它没有被多次触发
@Injectable({
providedIn: 'root'
})
export class CommonService {
constructor() {
this.getpatientId = this.bindPatientId.asObservable();
}
bindPatientId: Subject<number> = new Subject<number>();
getpatientId: Observable<number>;
setPatientId(patientId: number) {
this.bindPatientId.next(patientId);
}
bindTabId: Subject<number> = new Subject<number>();
}
Run Code Online (Sandbox Code Playgroud)
设置新值Subject
toggleProfile(patientId: number) {
this.commonService.setPatientId(patientId);
this.route.navigate(['/endrolPatient']);
}
Run Code Online (Sandbox Code Playgroud)
从另一个组件监听
ngOnInit() {
this._common.getpatientId.subscribe(
(res) => {
this.patientID = res;
console.log("console inside observable", this.patientID);
});
}
Run Code Online (Sandbox Code Playgroud)
在我的控制台中,当我通过时123- 我得到了console inside observable 123,但在第一个观察者休息后,所有订阅都加倍并在我的控制台中记录了两次 - 请帮助我修复它
这可能是因为您的组件正在被销毁并再次创建。因此,当您的组件销毁时,您必须销毁所有订阅。您可以在ngOnDestroy生命周期方法中执行此操作
代码:
class MyComponent implements OnInit, OnDestroy {
private sub: Subscription;
ngOnInit() {
this.sub = this._common.getpatientId.subscribe(
(res) => {
this.patientID = res;
console.log("console inside observable", this.patientID);
});
}
ngOnDestroy(){
this.sub.unsubscribe():
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2536 次 |
| 最近记录: |