I am struggling with what to do after authenticating my user. Once I receive the data, I want to redirect them to the appropriate page based on their role and display their name on that page. I have tried various methods, but it seems like when I try to call the router or a function, it's not in the same context. How can I resolve this issue?
Below is my login component code:
import { Component, OnInit } from '@angular/core';
import {User} from "../models/user";
import {AuthenticationService} from "../services/authentication.service";
import {Router} from "@angular/router";
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [AuthenticationService]
})
export class LoginComponent implements OnInit {
user: User = new User();
result: any;
constructor(private authenticationService: AuthenticationService,
private router: Router) {
}
loginAction() {
this.authenticationService.login(this.user)
.subscribe(function(result){
this.result = result;
console.log(this.result); // result : {token: "ABCDE....", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e195849295a195849295cf828e8c">[email protected]</a>", "username": "Jack James", role:"ADMIN"}
this.doSth(); //Never called, likely due to different context
this.router.navigate(['home']); // router not being found
// Need help with actions to redirect to another page and display currently logged-in user
},
err => {
// Log errors if any
console.log(err);
});
}
doSth(){
console.log("Do something");
}
ngOnInit() {
}
}