I am having an issue with user navigation on my application. After successfully signing in, users get redirected to the home page (/
), but they are unable to navigate by clicking any links on that page.
Upon further investigation, I discovered that moving
this.router.navigate(['/'], { relativeTo: this.route })
out of the subscribe
block in the login
method solves the problem and all functionality works as expected.
It seems there is an issue with calling this.router.navigate
from the subscribe
block. Can anyone help me figure out what's causing this behavior? Thanks.
Note: I found a similar question on StackOverflow here. The suggested solution of local assignment for router
did not work.
Angular version - 11
login(pwd: any){
this.loginService.login(usrname,pwd).subscribe(
(response) =>
{
console.log("success executed");
this.router.navigate(['/'], { relativeTo: this.route }).then(x => console.log("????? "+x));
return;
},
(error) =>
{
console.log("ERRR == "+JSON.stringify(error));
}
);
}
UPDATE
APP ROUTING MODULE.
{ path: '', loadChildren: () => import('./home-page/home-page.module').then(m => m.HomePageModule) , pathMatch:"full"},
{
path: 'signup',
loadChildren: () => import('./Reg/Reg.module').then(m => m.RegModule)
},
RegRoutingModule
import { SignUpComponent } from './sign-up/sign-up.component';
const routes: Routes = [
{ path: '', component: SignUpComponent },
{ path: 'signin', component: SignInComponent },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class RegRoutingModule { }
When users decide to sign in, they land on the Signup page (SignUpComponent
), and then click on the link SIGN IN (SignInComponent
). Both are lazy loaded modules.
The Homepage component is also a lazy loaded module.
UPDATE 2
HomePageRoutingModule
import { HomePageComponent } from './home-page.component';
const routes: Routes = [{ path: '', component: HomePageComponent },
];
@NgModule({
imports: [RouterModule.forChild(routes)],
exports: [RouterModule]
})
export class HomePageRoutingModule { }
UPDATE 3
<div>
<a [routerLink]="['profile/8']" routerLinkActive="active"> Go to Page 2</a>
<button (click)="navigateToProfile(profId)">
profile
</button>
</div>
navigateToProfile(profId: number) {
this.zone.run(() => {
this.router.navigate(['profile/'+profId]);
});
Note: Trying without using this.zone
had the same result. Could this issue be specific to Angular 11?
Note: This only happens when navigating from subscribe
; otherwise, it functions correctly.
UPDATE 4
Web service
SignIn(signinModel: SignIn): Observable<boolean> {
return this.httpClient.post<SignInResponse>(this.host + "/api/Sign", JSON.stringify(signinModel), { responseType: "json" })
.pipe(map(e => {
localStorage.setItem("user", e.token);
return e != null ? true:false;
}));
}
If I comment the line `` it all works fine. Adding the token to localstorage seems to be the problem.