To share variables between components Angular recommends the use of services.
Service are singletons, that is, only one instance exists during the application lifecycle and should be used to maintain the status of information between components.
A classic example in the use of services is precisely to keep the user information logged in.
@Injectable()
export class AccountService {
account?: Account
login(): void {
account = { id: 1111, name: 'Marcelo' }
}
isLoggedIn(): boolean {
return !!account
}
loggout(): void {
account = undefined
}
}
In the above service we use the class member account
to store logged user information.
The method login
must execute its login process and store the result in the Account variable.
The method isLoggedIn
validates the variable information account
and returns true
if it has been filled in, or if the user is logged in.
The method loggout
only configures the variable account
as undefined
or by removing the logged-in user information.
Once defined the service, you need to inject it into your Komponent to display the information, so as I understand do the following
@Component({
selector: 'page-login'
...
})
export class PaginaLoginComponent {
constructor(
private accountService: AccountService
) { }
isLoggedIn() {
return this.accountService.isLoggedIn()
}
}
and in the Component template PaginaLoginComponent
<div *ngIf="isLoggedIn()" class="alert alert-warning">
<span>Você foi deslogado</span>
</div>
Okay, I hope I’ve helped, remember to share information regarding the overall status of the application we use Angular services.
[]s
I edited your code and question and made it more intuitive for more elaborate answers to appear.
– Gunblades