I have two components: login and home. After the user logs in, it is redirected to home-report page. I want to display on toolbar the username (usersLogin.userLogin) that has logged in. I am able to display this.testUser="bla" on toolbar.
What I have tried:
The login.component.ts:
import { Component, OnInit, Injectable } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { MatSnackBar, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
import { Route, Router } from '@angular/router';
import { MatCardModule } from '@angular/material/card';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { analyzeAndValidateNgModules } from '@angular/compiler';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
usersLogin: any;
testUser:any;
ngOnInit() { }
userLog: string;
passLog: string;
submitLoading = false;
messageError: string;
messageOK: string;
data: any;
constructor(private snackBar: MatSnackBar, private router: Router, private http: HttpClient) { this.testUser="bla"}
onSubmitLogin(usersLogin: { userLogin: string, passLogin: string }) {
const headerDict = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
}
const requestOptions = {
headers: new HttpHeaders (headerDict),
};
this.http.post('http://localhost:54111/api/Login', usersLogin, requestOptions).subscribe(dataLogin => {
console.log( usersLogin.userLogin);
console.log("True or false: "+dataLogin)
this.testUser=usersLogin.userLogin;
console.log("testUser: "+ this.testUser);
if (dataLogin) {
this.snackBar.open('Login Successful', '', { duration: 1000 })
this.router.navigate([`Home`]);
} else {
this.snackBar.open('Login error', '', { duration: 1000 })
}
})
}
The home-report.component.ts:
import { Component, OnInit } from '@angular/core';
import { LoginComponent } from '../login/login.component';
@Component({
selector: 'app-home-report',
templateUrl: './home-report.component.html',
styleUrls: ['./home-report.component.css'],
providers: [LoginComponent]
})
export class HomeReportComponent implements OnInit {
userLogged: any;
usersLogin: any;
constructor(private utiliz: LoginComponent) { }
ngOnInit() {
this.userLogged=this.utiliz.testUser;
}
}
The home-report.component.html:
<mat-toolbar color="primary">
<span>Toolbar</span>
<div>
<mat-icon>account_circle</mat-icon>
{{userLogged}}
</div>
</mat-toolbar>
So my question is how could I get the usersLogin.userLogin from onSubmitLogin(...) method in order to display it in home-report component?