It is very weird that valueChanges doesn't trigger in below example. Is this a bug ? Do i have to unsubscribe from valueChanges?
subscription = Subscription.EMPTY;
constructor() {
this.form = new FormGroup({
id: new FormControl(0, { validators: [] })
});
}
ngOnInit(): void {
let sub = this.tokenId.valueChanges.subscribe((value: number) => this.tokenSelected(value));
//Value changes doesn't trigger because of this line
//but it works if i remove it.
this.subscription.add(sub);
}
get id() { return this.form.get('id')!; }
setId() {
this.id.setValue(1);
}
CodePudding user response:
It is very weird that valueChanges doesn't trigger in below example. Is this a bug ?
It's not a bug and valueChanges
doesn't trigger because it's already unsubscribed within ngOnInit
.
The issue is with the below assignment:
subscription = Subscription.EMPTY;
It creates a new Subscription and sets it's closed
property to true
. The closed
flag is used to indicate whether the Subscription has already been unsubscribed.
When you add a new subscription using add(sub)
, it internally checks if the subscription is already closed and since the closed
property was set to true
, the newly added subscription sub
is automatically unsubscribed. Hence the valueChanges
didn't triggered in your case.
Instead you can have the initialization as below:
subscription = new Subscription();