How to navigate to another component after subscription has finished?

320 Views Asked by At

I am sending a GET/POST request and wait for the response. After I get the response I would like to navigate to the "patients" page from dashboard page:

this.api.getData(body).subscribe((res) => {
    this.router.navigate(['/patients']);
});

However, I get the following error when router.navigate() is executed:

ERROR Error: Uncaught (in promise): TypeError: control._registerOnCollectionChange is not a function at cleanUpControl (forms.mjs:1614:17)
at FormControlDirective.ngOnDestroy (forms.mjs:5143:13)
at executeOnDestroys (core.mjs:7357:1)
at cleanUpView (core.mjs:7260:1)
at destroyViewTree (core.mjs:7093:1)
at destroyLView (core.mjs:7238:1)
at RootViewRef.destroy (core.mjs:21238:1)
at ComponentRef.destroy (core.mjs:21640:1)
at RouterOutlet.deactivate (router.mjs:2504:28)
at ActivateRoutes.deactivateRouteAndOutlet (router.mjs:2098:28)
at resolvePromise (zone.js:1211:1)
at resolvePromise (zone.js:1165:1)
at zone.js:1278:1
at _ZoneDelegate.invokeTask (zone.js:406:1)
at Object.onInvokeTask (core.mjs:25535:1)
at _ZoneDelegate.invokeTask (zone.js:405:1)
at Zone.runTask (zone.js:178:1)
at drainMicroTaskQueue (zone.js:585:1)
at ZoneTask.invokeTask [as invoke] (zone.js:491:1)
at invokeTask (zone.js:1661:1)

These are the routes:

const routes: Routes = [
  { path: '', redirectTo: 'dashboard', pathMatch: 'full' },
  { path: 'dashboard', component: MainComponent },
  { path: 'patients', pathMatch: 'full', component: PatientsListComponent }
];

This is the parent component:

<app-header></app-header>
<div class="main-container">
  <router-outlet></router-outlet>
</div>

Couldn't find anything about the error. What am I doing wrong here?

2

There are 2 best solutions below

0
Surya On

The error seems to be related to formcontrol which is not relevant to any of your routes or the code related to navigation. Look at the formcontrol usage in your component

0
Ankur Ishwar On

In my situation, I had a FormControl defined as follows:

control = new FormControl()

I subscribed to it without having a FormGroup. To resolve the issue, I created a FormGroup:

form = this.fb.group({
control: new FormControl(''),
});

Using forms in this manner resolved the problem. I couldn't find any answers or posts online addressing this issue, so I'm providing this solution.