I'm using Angular2 with ASP.NET Core MVC and managing manual URL navigation works fine, the server is loading my Home view with Angular2 successfully.
On user authentication, I'm setting up a session variable like this :
HttpHelper.HttpContext.Session.SetString("isLoggedIn", true.ToString() );
What I want is that after the user is in the application, if somewhat he wants to load a specific route by manually navigating to it, I want my service to call my ASP Controller to check if the user already got authenticated so that my guard allows the routing. Instead, the guard is by default set to false and I obviously get redirected to my login page.
Here is my ASP Controller method I want to call to update my IsLoggedIn value in my auth.service :
[HttpGet]
public IActionResult IsConnectedState()
{
if (!String.IsNullOrWhiteSpace(HttpHelper.HttpContext.Session.GetString("isLoggedIn")))
return Ok(true);
else
return Ok(false);
}
so that my AuthenticationGuard can call the AuthenticationService to update the boolean managing the authenticated state :
alert(this.authService.isLoggedIn);
if (!this.authService.isLoggedIn) {
this.authService.setupLoggedInState().subscribe(() => { });
}
with the following code updating the boolean in my auth.service :
setupLoggedInState() {
alert("Setting Up");
// Setting up the Http call
let lControllerAction: string = "/IsConnectedState";
let lControllerFullURL: string = this.controllerURL + lControllerAction;
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
// Call my ASP Controller IsConnectedState() method
return this.http.get(lControllerFullURL, options)
.map((res: any) => {
// Réponse reçue du WebService
let data = res.json();
alert(data);
if (data == true) {
this.isLoggedIn = true;
}
}
).catch(this.handleError);
}
When I do the authentication, and then manually navigate to an URL, my guard tells me that the boolean is indeed set to "false", and I also get the "Setting Up" when my service tries to call http.get. It seems to bug in the middle of the method, because I never get to the breakpoint I set in my ASP Controller. I get the following error which I don't understand :
"platform-browser.umd.js:937 EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'toString' of null"
Could it be because I don't call the service at the right moment in my auth.guard ? All my others call such as authentication work with http.post without any issue, so I don't really get where the problem is coming from...
Any help would be greatly appreciated.