Boa noite pessoal,
Estou criando uma aplicação web com Angular 9 usando o angular CLI.
Eu implementei para que só aparecer o menu da aplicação quando eu logar no sistema. Isso até funcionou, aperece os menus, mas minha homecomponent por exemplo não e quando dou um enter na url ele aparece a minha homecomponent, mas sem os menus.
Implementei a logica usando um EventEmitter()
Tela que aparece depois de logar
Tela que aparece quando dou enter na url depois de logar
Login.component.ts
import { UsuarioService } from ‘./…/…/…/services/usuario.service’;
import { Router } from ‘@angular/router’;
import { Component, OnInit, Injectable } from ‘@angular/core’;
import { UsuarioCorrente } from ‘src/app/model/usuario-corrente’;
import { Usuario } from ‘src/app/model/usuario’;
import { LocalStorageService } from ‘src/app/services/localstorage.service’;
import { SharedService } from ‘src/app/services/shared.service’;
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
usuario = new Usuario('','','','','','','','','','','','','',false,false,false);
message : String;
public shared: SharedService;
constructor(
private usuarioService: UsuarioService,
private router: Router,
private storage: LocalStorageService
) {
this.shared = SharedService.getInstance();
}
ngOnInit(): void {
}
logar(){
this.message = '';
this.usuarioService.login(this.usuario).subscribe((userAuthentication: UsuarioCorrente)=>{
this.storage.storeTokenOnLocalStorage(userAuthentication.token);
this.storage.storeUsuarioOnLocalStorage(userAuthentication.usuario);
this.shared.showTemplateEmitter.emit(true);
this.router.navigate(['/']);
}, err =>{
this.storage.deleteTokenFromLocalStorage();
this.storage.deleteUsuarioFromLocalStorage();
this.shared.showTemplateEmitter.emit(false);
this.message = 'Erro';
});
}
getFormGroupClass(isInvalid:boolean, isDirty:boolean):{}{
return {
'form-group':true,
'has-error': isInvalid && isDirty,
'has-sucess': !isInvalid && isDirty
}
}
}
**app.component.ts**
import { UsuarioService } from './services/usuario.service';
import { Component, ɵConsole } from '@angular/core';
import { LocalStorageService } from './services/localstorage.service';
import { SharedService } from './services/shared.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'BackupSafe';
showTemplate: boolean = false;
public shared: SharedService;
constructor(private userService: UsuarioService,private storage: LocalStorageService){
this.shared = SharedService.getInstance();
}
ngOnInit(){
this.shared.showTemplateEmitter.subscribe(
show => this.showTemplate = show
);
}
showContentWrapper(){
return {
'wrapper': this.storage.isLoggedIn()
}
}
}
shared.service.ts
import { Injectable, EventEmitter } from ‘@angular/core’;
@Injectable({
providedIn: ‘root’
})
export class SharedService {
public static instance : SharedService = null;
showTemplateEmitter = new EventEmitter();
constructor() {
return SharedService.instance = SharedService.instance || this;
}
public static getInstance(){
if(this.instance == null){
this.instance = new SharedService();
}
return this.instance;
}
}
Ai eu usei um diretiva do angular para exibir ou não o menu de acordo com esse EventEmitter
app.component.html
<app-header [hidden]="!showTemplate"></app-header>
<app-menu [hidden]="!showTemplate" ></app-menu>
<div [ngClass]="showContentWrapper()">
<section class="content-header">
</section>
<section class="content">
<router-outlet></router-outlet>
</section>
</div>
<app-footer [hidden]="!showTemplate"></app-footer>
home.component.html
<p>Esta é a minha home principal. Seja bem vindo!!!</p>
Alguém manja como corrigir esse problema?
Eu quero que sempre que ele estiver logado no sistema apareça os menus e o conteúdo que fica na
Para saber se estou logado eu tenho uma função que le o usuário gravado na local storage!
localstorage.service.ts
import { Usuario } from '../model/usuario';
import { Inject, Injectable, EventEmitter } from '@angular/core';
import { LOCAL_STORAGE, StorageService } from 'ngx-webstorage-service';
import { CryptografiaService } from './cryptografia.service';
@Injectable({
providedIn: 'root'
})
export class LocalStorageService {
public static instance : LocalStorageService = null;
STORAGE_TOKEN = 'token';
STORAGE_USUARIOLOGADO = 'usuariologado'
constructor(@Inject(LOCAL_STORAGE) private storage: StorageService,
private cryptografia:CryptografiaService) { }
getUsuarioLogadoFromLocalStorage(): Usuario{
// Retorna o usuário logado armazenado no local storage
let usuario = this.storage.get(this.STORAGE_USUARIOLOGADO)
if(usuario == null){
usuario = new Usuario('','','','','','','','','','','','','',false,false,false);
}
return usuario;
}
isLoggedIn():boolean{
let usuario = this.getUsuarioLogadoFromLocalStorage();
if(usuario == null){
return false;
}
return usuario.login != '';
}