Redeem data from another angular component

1

I have a component called login that when login completes the data of the user object, I need to get the "charge" field of this object and receive it in another component.

I've tried:

login.component.ts:

 public usuario: Usuario = new Usuario()

fazerLogin(email: string, password: string): void{
 //função que faz o login...
 this.enviaCargo(this.usuario.cargo)
}

  enviaCargo(cargo: string): void{ //aqui eu envio o valor para uma função do serviço.
    this.authService.setCargo(cargo);
  }

auth.service.ts:

 public cargo: string;

  setCargo(cargo: string){
    this.cargo = cargo;
  }

  getCargo(){
    return this.cargo;
  }

And then, in the component I want this given, I do:

private cargo: string;

  ngOnInit() {

    if (typeof this.cargo === 'undefined' || !this.cargo) { 
      this.cargo = this.loginService.getCargo();
    } 
 }

When the component receives the job, however, when I reload the page, I lose this data because it is only populated when I log in.

    
asked by anonymous 06.07.2018 / 17:21

1 answer

0

I think that setting in the localStorage is the best option, but if you want something different, try using the Event Emitter of the angle. Ex:

emitter.service.ts

import { Injectable, EventEmitter } from '@angular/core';

@Injectable()
export class EmitterService {

    static cargoEmitter= new EventEmitter();

}

login.component.ts

import { EmitterService } from './emitter.service';

public usuario: Usuario = new Usuario()

fazerLogin(email: string, password: string): void{
 //função que faz o login...
 this.enviaCargo(this.usuario.cargo)
}

  enviaCargo(cargo: string): void{ //aqui eu envio o valor para uma função do serviço.
    this.authService.setCargo(cargo);
    EmitterService.cargoEmitter.emit({ cargo: cargo });
  }

component that receives the data

import { EmitterService } from './emitter.service';
private cargo: string;

  ngOnInit() {

   EmitterService.cargoEmitter.subscribe(data => { 
      if(data){
        this.cargo = data;
      }
    });
 }
    
07.07.2018 / 07:38