I've encountered a peculiar issue.
There's a logout function that is activated whenever I receive a 401 response from any API I interact with.
The function looks like this:
constructor(
private router: Router,
) {}
logout(router1: Router) {
this.refreshTokenInProgress = false;
PreAngular.clearAll();
localStorage.clear();
if (window.location.href.indexOf("/public/login") == -1) {
router1.navigate(["/public/login"]);
}
}
This logout function is called in the following manner:
sendRequest(
request: HttpRequest<any>,
next: HttpHandler,
isCacheable: Boolean,
) {
return next.handle(request).pipe(
catchError((error) => {
if (error.status === 401 || (error.error != null && error.error.code == "0101")) {
this.logout(this.router);
//
return throwError(error);
}
}),
);
In my app, the scenario revolves around forcefully logging out a user from the database. If they are logged out and attempt to access any API, they receive a 401 response. My intention is for them to be logged out immediately upon receiving a 401 response. However, instead of logging out, an error is thrown in the typescript file of the page I am trying to route to after the forced logout. For example, an error is thrown on the ngOnInit function below:
ngOnInit() {
this.activeUserListingForm = this.createFormGroup();
this.isLogin = PreAngular.getUserInfo();
this.manager = "manager";
this.loadData();
}
loadData() {
this.formInProgress = true;
this.usersService
.getActiveUsersListing(
this.skip / this.pageSize,
this.pageSize,
this.buildSearchParameters(),
this.activeUserListingForm?.controls["searchInput"].value,
this.dynamicColumns,
this.sort,
)
.subscribe(
(response) => {
this.gridData = response;
console.log(this.gridData);
this.formInProgress = false;
if (!response) this.toastr.error("Error", "No Record Found");
},
(err) => {
console.log("Here in error" + err);
this.toastr.error("Something went wrong");
},
);
}
The console displays:
Here in errorTypeError: router1.navigate is not a function
The loadData function is in xyz.ts, which is the typescript file of the page I'm attempting to open after the forced logout, while the above code pertains to oauth.ts.
The aforementioned lines run in xyz.ts containing the loadData function:
console.log("Here in error" + err);
this.toastr.error("Something went wrong");
Upon applying a debugger, all the lines above the logout line execute successfully, but an error occurs on the this.router.navigate line.
Any advice or suggestions moving forward would be greatly appreciated.
Edit:
The error originates from the API file that I'm attempting to access. The aforementioned loadData code pertains to a sample API, so the error isn't consistently thrown in the same file. It depends on which API is being called.