Hey there! I am facing an issue with the router.navigate function in Angular. When I try to use it within a subscribe method for httpClient, it doesn't seem to work as expected. Can someone please help me understand why this is happening and how I can fix it?
Here's an example of the code:
Within the component:
getResponse(){
this.service.getRespone().subscribe((result) => {
//do something with response
this.router.navigate(['/secondcomponent']); //navigate to second component after completing the request
}, (error) => {
console.log(error);
alert('Your access token has expired. Please login again to obtain a new one');
this.router.navigate(['/login']);
});
}
In the service:
public getResponse(): Observable<Response> {
return this.http.get<Response>(this.API_URL , {
headers: new HttpHeaders({
Authorization: `Bearer ${this.authtoken}`
})
})
}
I have tried using
this.router.navigate(['/login'], { relativeTo: this.activatedRoute })
and this.ngZone.run(() => this.router.navigate(['/']))
but no luck.
*EDIT
In my app.modules file, I have defined my router configuration as follows:
{path: '', redirectTo: 'login', pathMatch: 'full'},
{path: 'login', component: LoginComponent},
{path: 'home', component: HomeComponent}, <- current location
{path: 'secondcomponent', component: SecondComponent}, <- destination after successful request
And in the component(home):
import { Router, ActivatedRoute } from '@angular/router';
constructor(private service :Service,private userservice:UserService,private router: Router,private route:ActivatedRoute,private ngZone: NgZone)
}