To share variables between components, Angular recommends using services.
Service are singletons, that is, only one instance exists during the application lifecycle and should be used to maintain information state between components.
A classic example of using services is just keeping 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 member of class account
to store the information of the logged in user.
The login
method should execute its login process and store the result in the variable account.
The isLoggedIn
method validates the information of the variable account
and returns true
if it has been filled, ie the user is logged in.
The loggout
method only sets the variable account
to undefined
or removes the information of the logged in user.
After defining the service, you need to inject it into your component 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>
Ready, I hope to have helped, please remember to share information regarding the overall state of the application we use Angular services.
[] s