I have a page that navigates to itself with different parameter. This makes the NgOnInit don’t be executed again. Sadly, in the NgOnInit I have an observable subscribed to deal with value changes in a particular form control. This works fine as long as the page doesn’t navigate to same page. Example:
ngOnInit() {
...
this.myForm.control['stateId'].valueChanges.pipe(startWith(''), pairwise()).subscribe(
([old, new]) = {
//do something with old and new values
}
);
...
}
Before, I had a similar issue dealing with the new parameter after navigating to same page, and I solved it by doing this:
ngOnInit() {
...
this.activatedRoute.params.subscribe(
(param) => {
//do something with param
}
);
...
}
How I can subscribe the valueChanges observable for a similar scenario?
2
We can use a switchMap to switch to the new valueChanges
listener when the route params changes this will solve the issue!
private subscription!: Subscription;
private sub!: Subscription = new Subscription();
ngOnInit() {
...
this.sub.add(
this.activatedRoute.params.pipe(
switchMap((param) => {
return this.myForm.control['stateId'].valueChanges.pipe(startWith(''), pairwise()).pipe(
tap(([old, new]) = {
//do something with old and new values
}));
})
));
...
}
2