Rescue data from another angular component

Asked

Viewed 691 times

1

I have a component called login that when you login fills the user object data, I need to take the "job" field of this object and receive in another component.

I tried to:

login.componentts.:

 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 that I want this data, I do:

private cargo: string;

  ngOnInit() {

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

When soon the component gets the job, but when I reload the page, I lose this data because it is only filled when you log in.

  • Why reload the page?

  • Because my idea is to use the position as Property Binding, if the position is different from 'a', apply the disabled. when I log in the element is disabled, but if I reload the page, the position becomes Undefined

  • You can save to a localStorage if applicable. localStorage.setItem("cargo", this.loginService.getCargo()): Logout removes this guy

  • i did not want to do with localstorage because this data can change in real time, does not seem to me to be the best alternative...

1 answer

1


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

emitter.service.ts

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

@Injectable()
export class EmitterService {

    static cargoEmitter= new EventEmitter();

}

login.componentts.

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 receiving the data

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

  ngOnInit() {

   EmitterService.cargoEmitter.subscribe(data => { 
      if(data){
        this.cargo = data;
      }
    });
 }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.